How to Call and Email in Swift

Originally Published at https://medium.com/better-programming/call-message-and-email-in-swift-a23df579e429

Hello iOS developers! Today we’re going to learn how to call, send a text message, and send email using Swift. I assume that you have a basic understanding of Swift syntax and have Xcode installed on your computer. Let’s get started!


Project Setup

First, let’s create a new project and name it “CallMessageEmail App.” When creating a new project, select “Swift” for “Language” and “Storyboard” for “UI Interface”—it’s easier for developing iOS apps. Your initial project should look like this:

Mac Book image

Now, we design our storyboard by drag-and-dropping the buttons and labels. Head over to the Storyboard and create three buttons. Label them “Call Me!!”, “Message Me!!” and “Email Me!!”, or whatever else you prefer. Your design should look basically like this:

Wireframe

Now, let’s run the app. You can see the button, but it’s not working yet. We’re going to code each button in the next step. In order to send either an email or message, we have to import the MessageUI library. Do this by typing import MessageUI at the top of the file after import UIKit. Everyone knows what UIKit is for. MessageUI will make life a lot easier while sending the messages and emails.


Sending Messages

After importing MessageUI, we’ll first write code for sending the message. Here’s what that looks like:

if (MFMessageComposeViewController.canSendText()) {
    let controller = MFMessageComposeViewController()
    controller.body = ""
    controller.recipients = ["1234567890"] //Here goes whom you wants to send the message
    controller.messageComposeDelegate = self as ? MFMessageComposeViewControllerDelegate
    self.present(controller, animated: true, completion: nil)
}
//This is just for testing purpose as when you run in the simulator, you cannot send the message.
else {
    print("Cannot send the message")
}
func messageComposeViewController(controller:
    MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
    //Displaying the message screen with animation.
    self.dismiss(animated: true, completion: nil)
}

Confused? I’ll explain.

Start from the last code block, messageComposeViewController. In this code block, you’re defining the controller as MFMessageComposeViewController and the result as MessageComposeResult. This tells the delegate that the user has finished composing the message. We wrote this first because it’d show an error when you define the above function if we didn’t. So far, your code should look like this: Message Me

Now, we add what we want to include in the body of the message, and the phone number of the recipient.

The code goes like this:

if (MFMessageComposeViewController.canSendText()) { //Checking whether we can send the message.
    let controller = MFMessageComposeViewController()
    controller.body = ""
    controller.recipients = ["0410171700"]
    controller.messageComposeDelegate = self as ? MFMessageComposeViewControllerDelegate
    self.present(controller, animated: true, completion: nil)
}
//This is just for testing because we cannot send the message from simulator.
else {
    print("Cannot send the message")
}

How does this code run? First, we check whether we can send the message to the recipient or not. This is just for testing. You can skip it if you like. Then, we define the message controller using the variable called controller:

let controller = MFMessageComposeViewController()

After defining the controller, we define the body of the message. By default, it should be blank. If you want to you can include body text that would automatically be populated. However, we won’t be doing that for this example.

controller.body = "" //Defining the body of the message

When defining the body of the message, we now include the message recipient’s phone number. Note that the recipient’s number is an array, meaning you can add more than one number at a time.

controller.recipients = ["012345678","0987654321"]

Now, we have to define our messageComposeDelegate from controller object to MFMessageComposeViewControllerDelegate as self. This is assigning the delegate to self.

controller.messageComposeDelegate = self as? MFMessageComposeViewControllerDelegate

When we click the MessageMe button, the controller will present to our view with animation and completion as nil.

self.present(controller, animated: true, completion: nil)

The complete code for sending the message is:

Sending the Meassage

Sending the emails

Next up, email. Take a look at the complete code first, and then we’ll go over each part.

if MFMailComposeViewController.canSendMail() {
    let mail = MFMailComposeViewController()
    mail.mailComposeDelegate = self as ? MFMailComposeViewControllerDelegate
    mail.setToRecipients(["[email protected]", "[email protected]"])
    mail.setMessageBody("<h1>Hello there, This is a test.<h1>", isHTML: true)
    present(mail, animated: true)
} else {
    print("Cannot send email")
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error ? ) {
    controller.dismiss(animated: true)
}

Just like we did for sending the message, we start by defining the under the sendEmail button. The code goes like this:

func mailComposeController(_ controller:MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}

There’s a slight change compared to sending the message. The extra code defines the error if your device is not connected to the Internet, which is out of the scope of this tutorial. Other than that, it should look familiar. The second step is to define the email body and email recipients. The code is similar to what we did to send the message. In an email, you can add more than one recipient. The only slight change you can see is that we have to define the isHTML as true after defining the email body. And you can write pure HTML code inside the body to make it look more attractive ,which you can try yourself. Now the code looks like: Call Me!


Making Calls

The last, and for me, the most fun part, is making a working call button. The complete code is below—it’s short and sweet, which is why it’s my favorite. I’ve made call buttons in other programming languages which took much longer, but in Swift, there’s only two lines of code required.

let url:NSURL = URL(string: "TEL://0123456789")! as NSURL
UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)

The first line defines the URL string for your phone number. The use of url: NSURL is to represent the location of a resource that bridges to URL defined in Apple’s documentation. Inside the URL string, define a string TEL://0123456789, which looks like a standard URL. We have to unwrap the URL string to NSURL for Swift to treat it as the URL. The following code is to open a small box which is a prompt to call the number or cancel it. The complete code looks like this:

Message Me


Conclusion

And now, you can call, send email, and message your friends! Enjoy your day! And always, keep learning , which will help you in many fields.

© 2021 Pramish Luitel • All rights preserved