Search code examples
iphoneiossmsmessageui

sending sms programmatically in iphone


How can you send an SMS programmatically to a particular number selected in the contact list in iPhone?


Solution

  • MFMessageComposeController is what you're looking for.

    To send an SMS, you're looking at something like this:

    #import <MessageUI/MessageUI.h>
    @interface myClass : NSObject <MFMessageComposeViewControllerDelegate>{
    }
    @end
    
    @implementation
    
    -(void)sendMessage{
        if([MFMessageComposeController canSendText]){
            MFMessageComposeController *smsComposer =
    [[MFMessageComposeController alloc] init]; smsComposer.recipients = [NSArray arrayWithObject:@"12345678"]; smsComposer.body = @"SMS BODY HERE"; smsComposer.delegate = self; [self presentModalViewController:smsComposer animated:NO]; } else{ //You probably want to show a UILocalNotification here. } } - (void)messageComposeViewController:(MFMessageComposeViewController *)controller
    didFinishWithResult:(MessageComposeResult)result{ /* You can use the MessageComposeResult to determine what happened to the
    message. I believe it tells you about sent, stored for sending later, failed
    or cancelled. */ [self dismissModalViewControllerAnimated:NO]; } @end

    That's the only way to send SMSs from your app at the moment. Unless you just want to open the SMS app. If you aren't worried about the body of the message, you can do this:

    NSString *smsURL = @"sms:12345678";
    NSURL *url = [NSURL URLWithString:smsURL];
    [[UIApplication sharedApplication] openURL:url];