Sending text messages in Swift with Twilio

March 22, 2018
Written by
Sam Agnew
Twilion

Screen Shot 2018-03-22 at 3.56.52 PM

Programmatically sending text messages is awesome, but doing so from an iOS app can be dangerous because it requires you to store your Twilio credentials in the app. With Swift’s ability to run on the server, you can avoid the risks of using Twilio client-side!

Let’s learn how to send an SMS with Twilio from our server using Swift.

If you just want to skip right to the point, here is all the code you need:

import Foundation
import Alamofire

if let accountSID = ProcessInfo.processInfo.environment["TWILIO_ACCOUNT_SID"], 
   let authToken = ProcessInfo.processInfo.environment["TWILIO_AUTH_TOKEN"] {

  let url = "https://api.twilio.com/2010-04-01/Accounts/\(accountSID)/Messages"
  let parameters = ["From": "YOUR_TWILIO_NUMBER", "To": "YOUR_PERSONAL_NUMBER", "Body": "Hello from Swift!"]

  Alamofire.request(url, method: .post, parameters: parameters)
    .authenticate(user: accountSID, password: authToken)
    .responseJSON { response in
      debugPrint(response)
  }

  RunLoop.main.run()
}

Read ahead to learn how to get this code working. Before moving on you’ll need to create a Twilio account if you haven’t already, and make sure you have Swift 4 installed.

What is this Alamofire thing?

In order to send a text message with Twilio, we will need to make an HTTP request to Twilio’s REST API. We will be using a library called Alamofire to do this. Check out this other tutorial for more general info on sending HTTP requests in Swift.

Since the premise of this is to run code from the server side, we are going to use Swift Package Manager to handle dependencies. Start by initiating a Swift package in the directory you want to run the code (I named my directory “SwiftSMS”):

swift package init --type executable

This will generate a Package.swift file for you, where we can add our dependencies. Open Package.swift and make sure it has the following code:

// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "SwiftSMS",
    dependencies: [
        .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.0.0")
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "SwiftSMS",
            dependencies: ["Alamofire"]),
    ]
)

Keep in mind that in the targets section, you may need to modify the name to fit your package.

Now that we are good to go with dependencies, it’s time to add code to our executable.

Sending an SMS in Swift

Before being able to send messages, you’ll need a Twilio phone number. You can buy a phone number here (it’s free if you’re using the number to test your code during development).

To send a text message, you’ll need to send your Twilio account SID and auth token as part of the request. You can find those in your Twilio Console. Store them in environment variables with the following command:

export TWILIO_ACCOUNT_SID='YOUR_ACCOUNT_SID'
export TWILIO_AUTH_TOKEN='YOUR_AUTH_TOKEN'

Now open the file main.swift in your Sources/SwiftSMS/ folder (replace “SwiftSMS” with whatever you named your project) and add the following code:

import Foundation
import Alamofire

if let accountSID = ProcessInfo.processInfo.environment["TWILIO_ACCOUNT_SID"], 
   let authToken = ProcessInfo.processInfo.environment["TWILIO_AUTH_TOKEN"] {

  let url = "https://api.twilio.com/2010-04-01/Accounts/\(accountSID)/Messages"
  let parameters = ["From": "YOUR_TWILIO_NUMBER", "To": "YOUR_PERSONAL_NUMBER", "Body": "Hello from Swift!"]

  Alamofire.request(url, method: .post, parameters: parameters)
    .authenticate(user: accountSID, password: authToken)
    .responseJSON { response in
      debugPrint(response)
  }

  RunLoop.main.run()
}

Remember to enter your Twilio phone number and personal phone number as the From and To values. Run it with this command, and you should receive a text message!

swift build && ./.build/debug/SwiftSMS

Now what?

You can send text messages using server side Swift now. Congrats! You might want to add this to an actual web application using a back end web framework for Swift such as Vapor. You also might want to try implementing this without using Alamofire if you don’t want to rely on dependencies. Check this post out to learn how to send HTTP requests in Swift 3 or 4.

If you want to do more with Swift and Twilio, you can check out these other posts:

If you have any other cool ideas, feel free to reach out and let me know or ask any questions: