Thursday 3 September 2009

Initiate a call with MonoTouch

Initiating calls, text messages and triggering other applications on the iPhone is a pretty basic requirement for MonoTouch applications - but it still took me a little while to "translate" the examples I found (eg developertips).






The mechanism is pretty simple - you just need to construct a Url with a specific 'scheme' and call the OpenURL method. I kept finding examples using self to reference OpenURL so it took me a second to figure out the method is actually on UIApplication. I'm working with iPhone OS 3.0 so OpenURL returns a bool if the action is 'possible': false if that scheme is not recognised on the device.
public partial class AppDelegate : UIApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
window.MakeKeyAndVisible();
buttonCall.TouchDown += delegate { // trigger action
NSUrl url = new NSUrl("tel:" + textfieldInput.Text);
if (!UIApplication.SharedApplication.OpenUrl(url))
{
var av = new UIAlertView("Not supported"
, "Scheme 'tel:' is not supported on this device"
, null
, "Ok thanks"
, null);
av.Show();
}
};
* Note: you can read about the singleton SharedApplication property in the UIApplication reference.

Some of the other common schemes look like this:
new NSUrl("sms:" + textfieldInput.Text);
new NSUrl("http://maps.google.com/maps?q=" + textfieldInput.Text); // opens Maps
new NSUrl("http://" + textfieldInput.Text); // opens Safari
new NSUrl("mailto:you@gmail.com?subject=" + textfieldInput.Text);
and two others I've added for testing are
new NSUrl("tweetie:///post?message=" + textfieldInput.Text);
new NSUrl("comgoogleearth://");
You can view the full code for the test app - Main.cs and MainWindow.xib.designer.cs - the Xib is basically a textfield and seven buttons - complete source in MonoTouch solution ZIP (14k).

Here's a link to Apple's Url Scheme Reference (PDF)
and two lists of the currently available url types: iPhone Url Schemes & AppLookup

1 comment:

  1. Hi Craig,

    Check out www.handleOpenURL.com

    You can use it's webservice to do query on e.g. 'twitter', you get back an XML list of known iPhone Twitter clients who incorporate a scheme to update Twitter.

    http://handleopenurl.com/x/search.xml?scheme=twitter

    You might want to use this to iterate through the returned schemes to see if there' a client on the users device.

    Best,
    Maarten

    ReplyDelete

Note: only a member of this blog may post a comment.