Officially, iPhone OS 4 is out of NDA and I can’t write a post on this. If you have been reading my blogs, you might already know how to send a in-app email Sending a in-app SMS is very similar to this, but with subtle differences.

Prior to iPhone OS 4, developers have to depend on


[[UIApplication sharedApplication] openURL: @"sms:12345678"];

The problem with this is not just that it closes your app, but there is no way to specify the body content of the SMS. Secondly, you are restricted to send the SMS to only one person. However, with the new MessageUI SMS controller, you can send SMS to multiple people at the same time. You can also pre-populate the SMS body field.
Developers of famous apps like Whatsapp Messenger, copy the SMS text content to clipboard and open the SMS app to allow users to paste the content. But with this newly allowed In-App SMS sheet, users can send SMS without quitting the app.

So, Let’s get started.

Step 1:

Import the MessageUI Framework into your project and #import the header file into the “.h” file of your controller where you want to open the In-App SMS sheet.

Step 2:

You might already have a button handler IBAction where you want to send the SMS. If not create a Button on your XIB file and write IBActions for it.

Step 3:

The real code

-(IBAction) sendInAppSMS:(id) sender
{
	MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
	if([MFMessageComposeViewController canSendText])
	{
		controller.body = @"Hello from Mugunth";
		controller.recipients = [NSArray arrayWithObjects:@"12345678", @"87654321", nil];
		controller.messageComposeDelegate = self;
		[self presentModalViewController:controller animated:YES];
	}
}

The most important part here is the line [MFMessageComposeViewController canSendText].
When sending a in-app email, you can choose to ignore this (atleast as of now) because most of the devices would have upgraded to iPhone OS 3 and all those devices would have the ability to send in-app email. However, the same doesn’t apply to SMS. Remember that even if a device is running iPhone OS 4, if it’s an iPod touch, it will never be abel to send SMS within app.
In this case, I have used a if condition to send the SMS. Practically speaking, you should enable/disable the button the user taps to send the sms based on this. You can add the code that does this in your viewDidLoad method.

Secondly, you have to set the messageComposeDelegate to self and not delegate. If you set the controller.delegate to self, you will not get the didFinishWithResult callback and the In-App SMS sheet will not close.

Step 4:

Implement Delegate Callbacks.
In your header file, implement the callbacks, MFMessageComposeViewControllerDelegate and UINavigationControllerDelegate. If you don’t you will get a warning at the line,

 controller.delegate = self;

You have to handle a callback method of MFMessageComposeViewControllerDelegate so as to dismiss the modal view controller.

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
	switch (result) {
		case MessageComposeResultCancelled:
			NSLog(@"Cancelled");
			break;
		case MessageComposeResultFailed:
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"MyApp" message:@"Unknown Error"
														   delegate:self cancelButtonTitle:@”OK” otherButtonTitles: nil];
			[alert show];
			[alert release];
			break;
		case MessageComposeResultSent:
 
			break;
		default:
			break;
	}
 
	[self dismissModalViewControllerAnimated:YES];
}

That’s it. Your app should now be able to send SMS using the new Message UI sheet.

Where the heck is MMS in this tutorial?

As on date, the MFMessageComposeViewController doesn’t support sending MMS. The controller.body is a NSString and setting a NSData pointer obviously crashes the app. Hopefully, one day, Apple will allow sending In-App MMS and I’ll probably blog about that too…

Follow me on Twitter

  • Rune

    Great, the inclusion of "body" support makes a world of difference! Thanks Apple (and thank you for sharing)

  • http://blogs.sun.ac.za/it/af Helmi

    Thanks Mugunth ! Professionally comunicated. Does the iOS4 also make provision for catching an SMS into the app ?

  • http://intensedebate.com/people/anka_ anka_

    The only drawback I found was that if sending the message really fails, the final result is not MessageComposeResultFailed as I expected, furthermore it is MessageComposeResultSent which is really confusing me.

  • kewl

    hi there,

    thank you for posting this.

    i have successfully coded the in App SMS. However my app crashed when launch at lower OS than iOS4.0 because of this. The error message is:

    dyld: Symbol not found: _OBJC_CLASS_$_MFMessageComposeViewController
    Referenced from: /Users/Library/Application Support/iPhone Simulator/3.2/Applications/

    Your help will be greatly appreciated.

  • kewl

    Continuity of the Error:

    Expected in: /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/MessageUI.framework/MessageUI

    • dejo

      kewl, you've probably figured this out already but in order to run on < iOS 4.0 you need to weak link the MessageUI.framework.

  • http://tooliphone.net tooliphone

    Hi everybody !
    I was trying to send SMS with a prefilled body message from my webapp, but without success…
    If I understand, it is now possible with iOS4 for NATIVE apps.
    But what about the webapps ?
    There is a way to do this with the "sms:" protocol set in href attribute, like for a "mailto:"
    example = Send me a SMS

    But with iPhone, the "body" attribute doesn't work… I was hoping that with iOS4 it should be possible, but I didn't manage to do this with iOS4… Did I miss something ?

    It is strange that iOS4 allows this body prefill functionnality but not through a webapp…

    Any advice ?
    Thank you in advance !

  • dejo

    There are a number of build errors associated with the MessageComposeResultFailed case.

    • Paul T

      I am getting a number of errors with this same case. Any ideas how to resolve the errors?
      Stray '342', '200', '235' several times each on the line UIAlertView *alert line.
      also
      Expected ';' before '{' on the line with the first {

      • Paul T

        Actually I figured out the Stray errors right after I posted this… there are tilted "s used in that line of code around the OK, change them to the straight " and the stray errors are solved.
        I'm still trying to figure out why it expects a ; before the first { though… :(

        • Chimonkey

          Did you manage to find error! I’m getting the same? Any suggestions? The error is Expected “;” before “}” and the error is point to “result” at he end of -(void) statement.

          #import
          #import

          @interface MediaPlayerViewController : UIViewController {

          IBOutlet UIButton *audioButton;
          SystemSoundID shortSound;

          AVAudioPlayer * audioPlayer;

          }

          - (void) messageComposeViewController:(MFMessageComposeViewController *) controller didFinishWithResult:(MessageComposeResult)result
          {

          switch (result) {
          case MessageComposeResultCancelled:
          NSLog(@”Cancelled”);
          break;
          case MessageComposeResultFailed:
          UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”MyApp” message:@”Unknown Error”
          delegate:self cancelButtonTitle:@”OK” otherButtonTitles: nil];
          [alert show];
          [alert release];
          break;
          case MessageComposeResultSent:

          break;
          default:
          break;
          }

          [self dismissModalViewControllerAnimated:YES];

          }

          • Baptiste

            I had this kind of error too but I managed to find out why:
            the switch statement comes from C, therefore: “Declaring a variable anywhere other than the beginning of the scope is illegal”.

            The correct code should then be:

            - (void) messageComposeViewController:(MFMessageComposeViewController *)
            controller didFinishWithResult:(MessageComposeResult)result
            {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”MyApp” message:@”Unknown Error”

            delegate:self cancelButtonTitle:@”OK” otherButtonTitles: nil];

            switch (result) {

            case MessageComposeResultCancelled:
            NSLog(@”Cancelled”);
            break;

            case MessageComposeResultFailed:
            [alert show];
            break;

            case MessageComposeResultSent:
            break;

            default:
            break;
            }

            [alert release];
            [self dismissModalViewControllerAnimated:YES];

            }

            Yet it seems like you can set C99 as a build directive in XCode, which might as well solve the problem and explain why it worked for Mugunth that way…

  • salim

    i m new to iPhone can u please send me the code. on below address

  • http://twitter.com/canzhiye @canzhiye

    i cant seem to set controller.body as my own string…

    NSString *smsBody = [[NSString alloc] initWithFormat:@"%@",displayText];
    controller.body = smsBody;
    controller.recipients = [NSArray arrayWithObjects:nil];
    controller.messageComposeDelegate = self;
    [self presentModalViewController:controller animated:YES];

    the body displays nothing

    • TJ Sartain

      @canzhiye: Had the same problem. The issue was that my string was sort of undefined by the time it got to the body assignment line. So what I did was make sure my string variable was retained appropriately and it all worked fine.

      @property (retain) NSString *smsBody;
      .
      .
      self.outputSMS = @"Some text to send.";

      • TJ Sartain

        Oops, that was supposed to be …

        self.smsBody = @"";

        • Drewgarcia6

          try

          picker.body = yourText.text;

  • jeff

    All this code does is create the SMS message, exit my application and open the SMS program with the phone number I am requesting to send to and the message I want to send. How do you send without opening the SMS app?

    • Dinesh Kumar

      Me too looking for the same query…Got answer?

  • Dinesh kumar

    Thanks Mugunth,Great help….Instead of showing the composer window and asking the user to click send button ,I want to programmatically send the sms.Can you help me please?

  • Santosh

    Actually, was too trying to send the sms without user intervention but it looks like iOS4+ only allow user to configure the "recipients and body" but seems like does not allow user to send the sms without taping the "send" button but through API.

    • longst

      I am wondering if you find solution for this thing: taping the "send" button through API…

  • faraz

    you used hard coaded phone number in your program can we use numbers from our contact list??

    • longst

      Yeah nice question. if you find some way to do that. Thank you

  • esramkumar

    Hi i saw your post it is very useful… but i need to know whether we can send sms at a particular time ie auto – sending sms at a particular time say sharp by 8 o clock the sms has to be sent and a push notification saying your sms has been sent….please help me..

  • Jesman

    Thanks Mugunth I try to work with Non-Weston Unicode UTF-8 Default Fonts from ios4.0

    please post more on NSUTF8STRING ENCORDING..

    THANKYOU.

  • Mohit2305

    We can not send the SMS programatically, because user need to hit the SEND button and we can not modify that

  • Pingback: links for 2010-12-27 | Alones world

  • rohan51

    Could you please post a sample project (in a zip file) that includes this functionality for those of us who are just starting out.
    Thanks, and great post!

  • Pingback: Quora

  • Groverpeyton

    How do I use the adress book to send the message

    • Bhavesh Kumbhani

      simply you open a addressbook (MFMessageComposeViewController) and get contact.

      • Wajahatch888

        How to implement adress book in your code , please tell me

  • Sunnysharmagts

    Hello,
    I did find the messageCompose in iOS 3.1.3 . though there was MailCompose framework. And also while sending an sms through [[UIApplication sharedApplication] openURL: @”sms:12345678″]; it said

    “Framwork not available Message”

    Is there a way of sending sms through iOS 3.1.3

  • http://twitter.com/stevem21m Steve McIntyre

    Thanks for this tutorial! Is it possible to share a link in the controller.body? I tried with no luck.

  • guru

    EXC_BAD_ACCESS when sending the SMS. why? Code is exactly as shown.

  • Pornume

     #import
    p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #d12c26}
    span.s1 {color: #78482f}

  • Koruk_19

    I am quite new at this. So, I have to ask about the implemetation of MFMessageComposeViewController. I include messageUI framework, but I can not see MFMessageComposeViewController class. Do I need to implement it? if I do, how? if I dont, how can I import it?
    Not: I use XCode 4.0.2

  • Koruk_19

    I am not interested in sending programatically. Sending by tapping a button is enough for now.

  • Zak Zhao77

    could i directly send the sms without open the message ui sheet?

    BR, Ben

    • shez

      Yes you can send sms without opening message ui sheet.

      • Skarkhanis

         Shez,
         Can you please elaborate how can we send sms without opening message ui sheet

  • Ujwal

    Is there a way to make the ‘send’ button get pressed automatically (programmatically)?. I mean to send sms with showing the sms composer view.

  • instyle

    i want the code how to check device is ipod when send sms inapps in iphone.i want to diasable
     -(IBAction) sendInAppSMS:(id) sender when device is ipod touch.is anybody have idea
    thanks

  • instyle

    i want the code how to check device is ipod when send sms inapps in iphone.i want to diasable
     -(IBAction) sendInAppSMS:(id) sender when device is ipod touch.is anybody have idea
    thanks

  • Pingback: iOS Tutorial: Sending In App Tweets | MKBlog

  • Donaldheinis

    I am newbie – is it ipossible to send SMS’s per application i.e. that an application is sending a SMS? – and that a application can receive / analyse an incoming SMS?
    TIA Guz

  • Bilal841

    Worked like a charm

  • http://twitter.com/IdanApps Idan

    Doesn’t work for me for some reason I cannot figure out myself.
    Can you post a sample code?

  • http://twitter.com/IdanApps Idan

    Doesn’t work for me for a reason I couldn’t figure out myself.
    Can you post a sample code?

  • Petrus Ali Saputra

    Can I send the message seamlessly? Thanks.

  • aaron

    mms is a simple http post over the 3g data connection (i believe the carrier rejects it if it’s over wifi). how can they stop you from performing an http post to an MMSC?

  • http://twitter.com/andrescanavesi Andrés Canavesi

    is there any possibility access to the send butto instance in order to click it programmatically ?, another option is click by its coordinates. To accomplish the very last we have to get the button coordinates like this: theButton.frame.origin.x and theButton.frame.origin.y. Still I can’t do that

  • Lance Bullion

    You made some decent points there. I looked on the internet for
    the issue and found most individuals will go along with with your blog.

  • Pingback: 뒤죽박죽 나의 뇌구조 분석 » 아이폰에서 문자를 보낼려면 어떻게 할까요?

  • Pingback: Useful iOS Development Tutorials & Resources | 聚疯堂

  • minDevApp

    How does the “dictaphone” app do to send sms attached audio file ?

  • Abhii Reddy

    this helped me a lot in setting the delegate. I was wondering how to set a delegate when it is giving a warning

  • Pingback: IPhone Tutorials « raja’s Blog

  • Pingback: How to programmatically send SMS on the iPhone? | Everyday I'm coding

  • captdragonman

    I’ve been developing natively for iOS and Android for 3 years and all I have to say is iOS sucks so much it hurts.

  • Milind Joshi

    Nice Tutorial :)

  • http://www.openxcell.com/ Justin Thomson

    The provided steps are promisingly looking helpful about how to send In App SMS. I am also one of mobile app developer and the regarding tutorial is totally informative about it. It’s totally worthy experienced source for those who are completely new in this field. Thanks for sharing some of inspirational features about iPhone app development in this source.

  • http://www.imobdevtech.com/ IOS APP Development

    It Grt Artical It is Help Full To ios App Developer….

  • Claude Raiola

    hi i am using jquery mobile and cordova i need to dynamically pass the mobile number and body of the sms to the compose sms screen,I have had someone else create the compose sms button that works when i hard code the mobile number and body message into the code. How can o dynamically have a jquery value that i currently have dynamically outputted on my page to be used in the code written to compose the sms which is object-c code. I would appreciate your comments send to info@trackingcentral.com.au