How To Make SMS Application in iOS Using Objective-C?

Hey everyone, as you know in our previous tutorial we have created a sample application through which we can send email to someone through the core email feature. Today in this tutorial we will be going to make use of the core SMS library. Through this app, you can send a text SMS message to someone using the same.

Which Framework to be Used

For this, we will be going to use message framework and through this, we can later call its object which is MFMessageComposeViewController. However, it will take care of the rest of the thing through which we can send the message to somebody easily.

Initial Setup

Now, let’s go ahead and start our initial setup first. To do this, head into the XCode application on your MacBook or Mac. Now, click on the ‘create new application’ section and select ‘single view application’ from the list shown in the snapshot below and hit next.

Now, after this, you need to give a name to your application. So that we can access it later for further editing. So, give a unique name to it and click on the next button as shown below.

Now save your application to a particular path from where you want to use it later and done.

Adding the Framework

We need to add the required framework to our application. Later, we can access the objects and related files inside the framework to implement the message UI in our app.

Head to the ‘Linked framework and Libraries’ section and add the following library inside it as shown in the snapshot below.

You can access it inside the view controller using the import command to import the library into the view controller file as shown.

#include <MessageUI/MessageUI.h>

You can make use of other frameworks as well like UIKit.framework and CoreGraphics.framework but this is one of the important frameworks that you need to add in your application in order to run it successfully.

Designing the User Interface

Now, we have done with the adding of the required framework in our app. We can now move ahead and create the design of our application. To do this, we will be going to make use of the table view object through which we can display a number of objects inside the table to use them later in the app.

Head into the interface builder section now and in your view controller first, add a view which covers the whole screen. Later after doing this, add a label and a table view of the object library by drag and drop process.

Inside the label add a text “List of Messages” to it and give it a background color of green or according to your choice.

Now, add a table view cell object from the same process into your table view and give a name to the reusable identifier to use it further in the app so that we can identify the cell easily.

Later on, we need one more thing which is a label on which we will be going to show our data in the table view. Add a label to the content view of the custom cell.

To make your design look better you can add a color to it. Same as I used for my application in the snapshot below.

Set the constraints for both the label and table view. For your label, give the constraints to Top space to view, the center horizontal, equal width and equal height to it. Below, it gives constraints to table view as top height label, the center horizontal, equal width and equal height to view.

Connecting the Outlets and Objects

Here, we are going to attach the objects which we have added previously to our view controller through the interface builder in the storyboard. However, before doing this head into the new file section and create a new cocoa touch class file as shown.

After doing this click next and select the UITableViewCell subclass. Assign the name to the file as “CustomTableViewCell” and click next and save it as shown below in the image.

Now, we have added the required file in the project. We can connect the objects to it and do this click on the assistant editor on the top right corner.

Start adding the objects to its related viewcontroller file.

First, Go to the view controller.h file and drag-drop the table view to it, name it as “customTableView” and click save as shown below.

Now, inside your CustomTableViewCell.h file and do the same thing with it, do it for the label which we have added previously in our cell as an object. Assign this object to the file and name it as “labelForTitle” and press ok.

Time for Coding

Now, we are good to go and we can move forward to the development part. First, we need to call the required delegates protocols for the table view. So add the following required code inside the viewcontroller.h file as shown below.

<UITableViewDelegate,UITableViewDataSource>

And later after doing this you also need to call the customTableViewCell file which we have created earlier in the same file as well.

Use #import “CustomTableViewCell.h” to call it.

After finishing with all these things your viewcontroller file will look like this:

#import <UIKit/UIKit.h>

#import "CustomTableViewCell.h"

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) IBOutlet UITableView *customTableView;

@end

Adding Table View Delegates and DataSource

Before we move ahead, we need to do some work on our viewcontroller.m file and to do this first add the following delegates and data source methods to your file as shown below.

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

  }

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

}

We can use these methods to call the required data inside our table view file so that things can work as per our requirements.

Now add the data in all the methods above one by one. If you have already created a table view then you will come to know that now you need to add an array through which you can show the data in it.

Adding Data to Methods

In the implementation section of the file, create an NSArray object and name it as titleArray as shown below:

@implementation ViewController{

    NSArray *titleArray;

}

Now inside the viewDidLoad method add elements to your array as shown below:

- (void)viewDidLoad {

    [super viewDidLoad];

    titleArray =[[NSArray alloc]initWithObjects:@"I am Busy! Will call you later",@"I am on my way",@"I am in a meeting",@"See you soon at cafeteria",@"Let's celebrate his birthday tomorrow", nil];

}

You can add as many objects as you want. For now, I am using these elements in my array. After this step, we need to add the data to the table view. To do this, first add the number of rows in section required which is according to the array we used here.

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return titleArray.count;

}

Next, we need to define the number of the section in a row. For this, add the return value as 1 in this as shown below:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;

}

Similar to this, we need to identify the cell for the row at indexPath which will call our custom cell. For this add the code in cellForRowAtIndexPath method as shown below:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];

    if (cell) {

        cell.labelForTitle.text = [titleArray objectAtIndex:indexPath.row];

    }

    return cell;

 }

Apart from this, we are going to use two more methods for table view one for height and another for selection of a particular object from the table view.

But first, we will be going to create a function in which we can save the index value from the array selected. And on the basis of this, the data will be called to send SMS to that data only.

Now, create the function first as shown below.

- (void)showSmsTitles:(NSString*)file {

   }

And later add the code inside the didSelectRow at index.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSString *selectedTitle = [titleArray objectAtIndex:indexPath.row];

    [self showSmsTitles:selectedTitle];

}

Calling Message Service Data

Now, we have added the required data for the table view. We can further add the library data for the SMS service to be called.

First, add the delegate protocol for the message library as shown below inside the viewcontroller.m file.

#import "ViewController.h"

#include <MessageUI/MessageUI.h>

@interface ViewController ()<MFMessageComposeViewControllerDelegate>

@end

Now after doing this we can add the code to our custom function which we have created earlier.

- (void)showSmsTitles:(NSString*)file {

   NSString *message = [NSString stringWithFormat:@"%@", file];

    /* here you can use any number according to you which will become the recipient to whom you want to send sms */

    NSArray *recipentNumber = @[@"12345678"];

    if (![MFMessageComposeViewController canSendText]) {

          /*if sms service will not be available then this code will resume */

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"SMS Service is not available for this device!" preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *action = [UIAlertAction actionWithTitle:@"Okay" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            [alert dismissViewControllerAnimated:YES completion:nil];

        }];

        [alert addAction:action];

        [self presentViewController:alert animated:YES completion:nil];

     }

    else{

        MFMessageComposeViewController *messageController = [[MFMessageComposeViewController alloc] init];

        messageController.messageComposeDelegate = self;

        [messageController setRecipients:recipentNumber];

        [messageController setBody:message];

          // Present message view controller on screen

        [self presentViewController:messageController animated:YES completion:nil];

    }

}

As you can see MFMessageComposeViewController is a class, It can be used to open the default iOS Message Interface to send the SMS to someone.

In the above code, we are doing the same thing. And with the recipient, we are adding a number inside our recipient section of the app to send an SMS.

We can also handle the event where the method will be called after the SMS action gets performed by the user. This method is known as didFinishWithResult: It lets us know whether user sends the message or cancel it or something else happened with SMS.

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

{

    switch (result) {

        case MessageComposeResultCancelled:

            break;

    case MessageComposeResultFailed:

        {

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"Failed to send SMS!" preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *action = [UIAlertAction actionWithTitle:@"Okay" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                [alert dismissViewControllerAnimated:YES completion:nil];

            }];

            [alert addAction:action];

            [self presentViewController:alert animated:YES completion:nil];

            break;

        }        

        case MessageComposeResultSent:

            break;

         default:

            break;

    }  

    [self dismissViewControllerAnimated:YES completion:nil];

}

Hence, I am going to add an alert message to the failed section of this method. When the message was unable to send then it will call the alert message and will show you the related message.

Increase the height of Table

Previously, we have added a method to handle the height of table view.

However, this is an optional part of the blog but I am adding the code for this also if you want to increase the height of your table view. Add it to your viewcontroller.m file as shown below.

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return UITableViewAutomaticDimension;

}

And after doing this in your viewdidload method add the code to define the height of the row.

customTableView.estimatedRowHeight = 200;

    customTableView.rowHeight = UITableViewAutomaticDimension;

Run the Application

Now, Run the application and you will see a list of titles available to send SMS to the user as shown below image.

Similarly, if you click on a particular message then it will show result according to it.

The above error appears because we are running it on the iPhone simulator. To demonstrate it, we are going to run this application on the real device i.e. an iPhone then you will find a popup appear in front of you. This will be going to show you the message view to send a message to someone.

Conclusion

That’s it, we have successfully implemented the message service inside our custom application. I hope you will find this tutorial useful for your apps as well. For more tutorials like this stay tuned with us and let us know what you think about it in the comments section below. Similarly, we are going to make some tutorials on swift language as well. So keep in touch. Thank you!

Latest posts by Rahul Huria (see all)

Leave a Comment