Search code examples
iosobjective-cmfmessagecomposeviewcontroller

Send a text message directly via an IBAction (Objective-C)


How do I send a text message (using MFMessageComposeViewController) directly via an IBAction? Like, when the button is pressed, a text message is sent with a preset number, and no keyboard shows up or anything. Just an alert saying "SMS was sent successfully," for example.

All the coding is done, except for this "direct sending-function".


Solution

  • Well, you can't technically "auto-send" the message, because it will require user confirmation to go through.

    You can, however, set up the message's contents and recipient(s) using MFMessageComposeViewController (quite a mouthful) and display a dialog that will require one extra tap to send.

    To have access to that dialog, you'll have to #import <MessageUI/MessageUI.h> and add MFMessageComposeViewControllerDelegate to your view controller declaration in your header file.

    Then, you can write the IBAction. First, you want to check that the device can actually send messages with text content using canSendText. Then, you'll create the view controller, populate it with data, and present the dialog.

    - (IBAction)sendMessage:(UIButton *)sender {
        if([MFMessageComposeViewController canSendText]) {
            MFMessageComposeViewController *messageController = [[MFMessageComposeViewController alloc] init]; // Create message VC
            messageController.messageComposeDelegate = self; // Set delegate to current instance
    
            NSMutableArray *recipients = [[NSMutableArray alloc] init]; // Create an array to hold the recipients
            [recipients addObject:@"555-555-5555"]; // Append example phone number to array
            messageController.recipients = recipients; // Set the recipients of the message to the created array
    
            messageController.body = @"Example message"; // Set initial text to example message
    
            dispatch_async(dispatch_get_main_queue(), ^{ // Present VC when possible
                [self presentViewController:messageController animated:YES completion:NULL];
            });
        }
    }
    

    One last thing: you have to implement a delegate method to tell the message view controller to dismiss when the user presses "cancel" in the send dialog:

    - (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
        [self dismissViewControllerAnimated:YES completion:NULL];
    }