10 min read

(For more resources on this topic, see here.)

Mobile devices offer a handful of features to the user. Creating an application that interacts with those features to provide a complete experience to users can surely be considered as an advantage.

In this article, we will discuss some of the most common features of iOS and how to integrate some or all of their functionality to our applications. We will see how to offer the user the ability to make telephone calls and send SMS and e-mails, either by using the native platform applications, or by integrating the native user interface in our projects. Also, we will discuss the following components:

  • MFMessageComposeViewController: This controller is suitable for sending text (SMS) messagesIntegrating iOS Features
  • MFMailComposeViewController: This is the controller for sending e-mails with or without attachments
  • ABAddressBook: This is the class that provides us access to the address book database
  • ABPersonViewController: This is the controller that displays and/or edits contact information from the address book
  • EKEventStore: This is the class that is responsible for managing calendar events

Furthermore, we will learn how to read and save contact information, how to display contact details, and interact with the device calendar.

Note that some of the examples in this article will require a device. For example, the simulator does not contain the messaging application. To deploy to a device, you will need to enroll as an iOS Developer through Apple’s Developer Portal and obtain a commercial license of MonoTouch.

Starting phone calls

In this recipe, we will learn how to invoke the native phone application to allow the user to place a call.

Getting ready

Create a new project in MonoDevelop, and name it PhoneCallApp.

The native phone application is not available on the simulator. It is only available on an iPhone device.

How to do it…

  1. Add a button on the view of MainController, and override the ViewDidLoad method. Implement it with the following code. Replace the number with a real phone number, if you actually want the call to be placed:

    this.buttonCall.TouchUpInside += delegate {
      NSUrl url = new NSUrl(“tel:+123456789012”);
      if (UIApplication.SharedApplication.CanOpenUrl(url)){
        UIApplication.SharedApplication.OpenUrl(url);
      }  else{
        Console.WriteLine(“Cannot open url: {0}”, url.AbsoluteString);
      }
    } ;

    
    
  2. Compile and run the application on the device. Tap the Call! button to start the call. The following screenshot shows the phone application placing a call:

How it works…

Through the UIApplication.SharedApplication static property, we have access to the application’s UIApplication object. We can use its OpenUrl method, which accepts an NSUrl variable to initiate a call:

UIApplication.SharedApplication.OpenUrl(url);

Since not all iOS devices support the native phone application, it would be useful to check for availability frst:

if (UIApplication.SharedApplication.CanOpenUrl(url))


 

When the OpenUrl method is called, the native phone application will be executed, and it will start calling the number immediately. Note that the tel: prefx is needed to initiate the call.

There’s more…

MonoTouch also supports the CoreTelephony framework, through the MonoTouch. CoreTelephony namespace. This is a simple framework that provides information on call state, connection, carrier info, and so on. Note that when a call starts, the native phone application enters into the foreground, causing the application to be suspended. The following is a simple usage of the CoreTelephony framework:

CTCallCenter callCenter = new CTCallCenter();
callCenter.CallEventHandler = delegate(CTCall call) {
  Console.WriteLine(call.CallState);
} ;


 

Note that the handler is assigned with an equals sign (=) instead of the common plus-equals (+=) combination. This is because CallEventHandler is a property and not an event. When the application enters into the background, events are not distributed to it. Only the last occured event will be distributed when the application returns to the foreground.

More info on OpenUrl

The OpenUrl method can be used to open various native and non-native applications. For example, to open a web page in Safari, just create an NSUrl object with the following link:

NSUrl url = new NSUrl(“http://www.packtpub.com“);


 

See also

In this article:

  • Sending text messages and e-mails

Sending text messages and e-mails

In this recipe, we will learn how to invoke the native mail and messaging applications within our own application.

Getting ready

Create a new project in MonoDevelop, and name it SendTextApp.

How to do it…

  1. Add two buttons on the main view of MainController. Override the ViewDidLoad method of the MainController class, and implement it with the following code:

    this.buttonSendText.TouchUpInside += delegate {
      NSUrl textUrl = new NSUrl(“sms:”);
      if (UIApplication.SharedApplication.CanOpenUrl(textUrl)){
        UIApplication.SharedApplication.OpenUrl(textUrl);
      } else{
        Console.WriteLine(“Cannot send text message!”);
      }
    } ;
    this.buttonSendEmail.TouchUpInside += delegate {
      NSUrl emailUrl = new NSUrl(“mailto:”);
      if (UIApplication.SharedApplication.CanOpenUrl(emailUrl)){
        UIApplication.SharedApplication.OpenUrl(emailUrl);
      } else{
        Console.WriteLine(“Cannot send e-mail message!”);
      }
    } ;

    
    
  2. Compile and run the application on the device. Tap on one of the buttons to open the corresponding application.

How it works…

Once again, using the OpenUrl method, we can send text or e-mail messages. In this example code, just using the sms: prefx will open the native text messaging application. Adding a cell phone number after the sms: prefx will open the native messaging application:

UIApplication.SharedApplication.OpenUrl(new
NSUrl(“sms:+123456789012”));


 

 

Apart from the recipient number, there is no other data that can be set before the native text message application is displayed.

For opening the native e-mail application, the process is similar. Passing the mailto: prefx opens the edit mail controller.

UIApplication.SharedApplication.OpenUrl(new NSUrl(“mailto:”));


 

 

The mailto: url

scheme supports various parameters for customizing an e-mail message. These parameters allows us to enter sender address, subject, and message:

UIApplication.SharedApplication.OpenUrl(“mailto:recipient@example.
com?subject=Email%20with%20MonoTouch!&body=This%20is%20the%20
message%20body!”);


There’s more…

Although iOS provides access to opening the native messaging applications, pre-defning message content in the case of e-mails, this is where the control from inside the application stops. There is no way of actually sending the message through code. It is the user that will decide whether to send the message or not.

More info on opening external applications

The OpenUrl method provides an interface for opening the native messaging applications. Opening external applications has one drawback: the application that calls the OpenUrl method transitions to the background. Up to iOS version 3.*, this was the only way of providing messaging through an application. Since iOS version 4.0, Apple has provided the messaging controllers to the SDK. The following recipes discuss their usage.

See also

In this article:

  • Starting phone calls
  • Using text messaging in our application

Using text messaging in our application

In this recipe, we will learn how to provide text messaging functionality within our application using the native messaging user interface.

Getting ready

Create a new project in MonoDevelop, and name it TextMessageApp.

How to do it…

  1. Add a button on the view of MainController. Enter the following using directive in the MainController.cs fle:

    using MonoTouch.MessageUI;

    
    
  2. Implement the ViewDidLoad method with the following code, changing the recipient number and/or the message body at your discretion:

    private MFMessageComposeViewController messageController;
    public override void ViewDidLoad (){
      base.ViewDidLoad ();
      this.buttonSendMessage.TouchUpInside += delegate {
        if (MFMessageComposeViewController.CanSendText){
          this.messageController = new 
            MFMessageComposeViewController();
          this.messageController.Recipients = new 
            string[] { “+123456789012” };
          this.messageController.Body = “Text from MonoTouch”;
          this.messageController.MessageComposeDelegate = 
            new MessageComposerDelegate();
          this.PresentModalViewController(
            this.messageController, true);
        } else{
          Console.WriteLine(“Cannot send text message!”);
        }
      } ;
    }

    
    
  3. Add the following nested class:

    private class MessageComposerDelegate : 
      MFMessageComposeViewControllerDelegate{
      public override void Finished (MFMessageComposeViewController
        controller, MessageComposeResult result){
        switch (result){
          case MessageComposeResult.Sent:
            Console.WriteLine(“Message sent!”);
          break;
          case MessageComposeResult.Cancelled:
            Console.WriteLine(“Message cancelled!”);
          break;
          default:
            Console.WriteLine(“Message sending failed!”);
          break;
        }
        controller.DismissModalViewControllerAnimated(true);
      }
    }

    
    
  4. Compile and run the application on the device.
  5. Tap the Send message button to open the message controller. Tap the Send button to send the message, or the Cancel button to return to the application.

How it works…

The MonoTouch.MessageUI namespace contains the necessary UI elements that allow us to implement messaging in an iOS application. For text messaging (SMS), we need the MFMessageComposeViewController class.

Only the iPhone is capable of sending text messages out of the box. With iOS 5, both the iPod and the iPad can send text messages, but the user might not have enabled this feature on the device. For this reason, checking for availability is the best practice. The MFMessageComposeViewController class contains a static method, named CanSendText, which returns a boolean value indicating whether we can use this functionality. The important thing in this case is that we should check if sending text messages is available prior to initializing the controller. This is because when you try to initialize the controller on a device that does not support text messaging, or the simulator, you will get the following message on the screen:

 

To determine when the user has taken action in the message UI, we implement a Delegate object and override the Finished method:

private class MessageComposerDelegate : 
  MFMessageComposeViewControllerDelegate


 

Another option, provided by MonoTouch, is to subscribe to the Finished event of the MFMessageComposeViewController class.

Inside the Finished method, we can provide functionality according to the MessageComposeResult parameter. Its value can be one of the following three:

  • Sent: This value indicates that the message was sent successfully
  • Cancelled: This value indicates that the user has tapped the Cancel button, and the message will not be sent
  • Failed: This value indicates that message sending failed

The last thing to do is to dismiss the message controller, which is done as follows:

controller.DismissModalViewControllerAnimated(true);


 

After initializing the controller, we can set the recipients and body message to the appropriate properties:

this.messageController.Recipients = new string[] { “+123456789012” };
this.messageController.Body = “Text from MonoTouch”;


 

The Recipients property accepts a string array that allows for multiple recipient numbers. You may have noticed that the Delegate object for the message controller is set to its MessageComposeDelegate property, instead of the common Delegate. This is because the MFMessageComposeViewController class directly inherits from the UINavigationController class, so the Delegate property accepts values of the type UINavigationControllerDelegate.

There’s more…

The fact that the SDK provides the user interface to send text messages does not mean that it is customizable. Just like invoking the native messaging application, it is the user who will decide whether to send the message or discard it. In fact, after the controller is presented on the screen, any attempts to change the actual object or any of its properties will simply fail. Furthermore, the user can change or delete both the recipient and the message body. The real beneft though is that the messaging user interface is displayed within our application, instead of running separately.

SMS only

The MFMessageComposeViewController can only be used for sending Short Message Service (SMS) messages and not Multimedia Messaging Service (MMS).

LEAVE A REPLY

Please enter your comment!
Please enter your name here