iOS-Implementation of Short Message Function

Posted by nadeem14375 on Tue, 04 Jun 2019 03:00:15 +0200

The function of sending short messages is indispensable for an APP that needs channel expansion. However, when I first saw this demand, I was confused, because I had not met before, out of fear of the unknown, when I was assigned to do this task, I actually refused, but there is no way to let me be a soldier, can only be tough on the scalp. After consulting some information, I found that this function is very simple to do and can be solved in less than ten minutes. Now let's talk about how to implement this function.

First of all, let's introduce the simplest method. It only needs one line of code. The code is as follows:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://800888"]];

However, although this code is simple, the shortcomings are obvious. This code belongs to the external call of the program, that is to say, it jumps out of the app program itself and uses the SMS function to send SMS messages. When clicking the Cancel button on the sending SMS page, it returns to the SMS function page of the mobile phone, not the app program. Moreover, this method can not pass in the default text messages, and needs to input manually, which may not meet the requirements. So:

One thing we need to know is that Apple officially has a framework for sending short messages called MessageUI, which can solve all these problems and is easy to implement. Let's introduce the use of this framework.

Before having a big meal, let's start with a few dishes:

  1. Import framework: MessageUI.framework

    Screen snapshot 2017-08-16 17.22.50.png

2. Import header: #import <MessageUI/MessageUI.h>

3. Adding protocol: <MFMessage ComposeViewController Delegate>


Screen snapshot 2017-08-16 17.32.28.png

After adding the protocol, the first thing we think about is how to implement the protocol, but we can't rush. We have to check whether the device can send short messages. As follows:

- (void)showSMSPicker:(id)sender
{
     /**
     You must check whether the current device can send a short message before attempting to create an instance of MFMessageComposeViewController
     .  If the device cannot send a short message,
     [[MFMessageComposeViewController alloc] init]It will return to nil. Your application is invoked with an empty view controller
      -presentViewController It can lead to collapse.
      **/
    if ([MFMessageComposeViewController canSendText])
        // The device can send email.
    {
        [self displaySMSComposerSheet];
    }
    else
        // The device can not send email.
    {
        self.feedbackMsg.hidden = NO;
        self.feedbackMsg.text = @"Device not configured to send SMS.";
    }
}

- (void)displaySMSComposerSheet
{
    MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
    picker.messageComposeDelegate = self;
    
    //You can specify one or more pre-configured recipients. Users have an option controller to delete or add recipients from message editor view
    //You can specify the initial message text that will appear in the message editor view controller.
    
    picker.recipients = @[@"Phone number here"];//An array of cell phone numbers for sending short messages, in which one is sent singly and multiple is sent in groups.
    picker.body       = @"Hello from California!"; //Subject Content of Short Message
    
    [self presentViewController:picker animated:YES completion:NULL];
}

To detect whether a short message can be sent or not, a trigger event is needed. The code is as follows:


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(140, 100, 100, 100)];
    button.backgroundColor = [UIColor blackColor];
    [button setTitle:@"Send short messages" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(showSMSPicker:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    UILabel * feedbackMsg =  [[UILabel alloc]initWithFrame:CGRectMake(10, 300, self.view.frame.size.width -20, 30)];
    feedbackMsg.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:feedbackMsg];
    self.feedbackMsg = feedbackMsg;
}


Well, it's time to implement the protocol approach:

// -------------------------------------------------------------------------------
//  messageComposeViewController:didFinishWithResult:
//  Dismisses the message composition interface when users tap Cancel or Send.
//  Proceeds to update the feedback message field with the result of the
//  operation.
//  Close the message composition interface when the user clicks Cancel or Send.
//  Receive the result operation of the update feedback message field.
// -------------------------------------------------------------------------------
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller 
              didFinishWithResult:(MessageComposeResult)result
{
    self.feedbackMsg.hidden = NO;
    // Notifies users about errors associated with the interface
    // Notify users of interface-related errors
    switch (result)
    {
        case MessageComposeResultCancelled: //cancel
            self.feedbackMsg.text = @"Result: SMS sending canceled";
            break;
        case MessageComposeResultSent: //Send out
            self.feedbackMsg.text = @"Result: SMS sent";
            break;
        case MessageComposeResultFailed: //fail
            self.feedbackMsg.text = @"Result: SMS sending failed";
            break;
        default: //default
            self.feedbackMsg.text = @"Result: SMS not sent";
            break;
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}

Demo runs as follows:


IMG_1445.PNG

IMG_1446.PNG

IMG_1447.PNG

So far, our function of sending short messages has been realized, is it simple? However, the year was also encouraged ah, so close-up of this article to commemorate the days of encouragement.

Reference Articles

Official Documents

Topics: snapshot less Mobile