How to call Twilio Functions from iOS

Twilio Functions are a perfect fit for mobile app developers. You can focus on writing your app, and let Twilio host and run the server code you need.

You don't need a special SDK to call Twilio Functions from your mobile app - your function will respond to a normal HTTP call, making it easy to call from standard iOS Networking code.

In this guide, we'll show you how to set up a simple Twilio Function, call it from a web browser, and then call that function from an iOS application. Our function will return a joke as a string. You could extend it to make it choose a random joke from a list, or by category. We'll keep it simple, and just return a hard coded string.

At the end of the guide, we'll have a link to the rest of the Functions documentation, where you can learn more about debugging your function.

Create a Twilio Function

Let's start by visiting the Functions page in the Console: 

Manage Twilio Functions from the Console

Click the big Create a Function button, and you'll get this window to appear with a choice of templates for your function:

Add a New Function

As you can see, several things you might have had to spin up a whole server for before are now templates that you can easily use as a base for customization.

We're going to write our own Function, so choose the Blank template, and then click the Create button.

You'll see a new Twilio function appear, with a few options we'll go over:

Blank Function

The Function Name is "Blank" - you use this as a descriptive name for your function in the Console, so feel free to change that to something more descriptive. In our case, we're going to make a "Joke of the Day" function, so change the Function Name to "Joke of the Day".

For the path, your account will have an auto-assigned domain name that you use for your account's Twilio Functions. Because you might have more than one function, you will want to have each function listen on a different path. For our purposes, we will put "/joke" in for the path.

Under Access Control, we could have this Function check for a valid Twilio signature before responding. This is very useful for creating webhooks with Twilio Functions, but we will be calling this Twilio function directly from the mobile application, so the inbound HTTP request will not be signed by Twilio. Be sure to leave this checkbox unchecked.

The Event dropdown is also useful for writing a webhook with Twilio Functions (you can choose between Incoming Message or Incoming Voice Call), but you won't need to select either one of these to use the a Twilio Function from a mobile app.

Last, we'll need to edit the template code that was included - by default, it comes with some code to return TwiML. We're only going to return a joke. And it's a bad joke.

Joke of the Day Twilio Function

Loading Code Samples...
Language
SDK Version:
  • 3.x
exports.handler = function(context, event, callback) {
  const joke = 'How many apples grow on a tree? They all do!';
  callback(null, joke);
};
Return a Joke with a Simple Twilio Function

Copy that code into the Twilio Functions code editor. Please, change the joke to something better - it won't be hard to do. Press the "Save" button to save that code, and Twilio will deploy your function for you.

A little bit about what that code does - a Twilio Function gets three arguments - context, event, and callback.

The context contains configuration you set on your Twilio Function - you can set environment variables through the console that get passed to the function every time it is executed, and you can also check a box to pass an auth token with your account SID as well. You can use that combination of account SID and auth token to initialize a Twilio REST Client, or use a pre-initialized one that is available on the context.

The event contains any GET or POST parameters passed to the function at the time it was called.

The callback is required for your function to finish processing - after you complete everything you need to do with your function, make sure to call the callback function. The callback has two arguments. The first argument is an error description - if something went wrong, pass a string back with a human-readable description of the error. If everything went well, this argument will be null. The second argument is the result. The result can be either a string, a Javascript object, or TwiML. A Javascript object will be converted to JSON, and a TwiML object will be converted to XML.

Call a Twilio Function from the Web

Calling your new Twilio function from the web couldn't be easier. Simply get the URL to your function by clicking the "Copy" button next to the path, and then paste the URL into any web browser (you don't have to be authenticated with Twilio). You'll get a text response of whatever you return from your function!

Call a Twilio Function from iOS

We can use the standard iOS library to call our Twilio Function. The URLSession (NSURLSession with Objective-C) class lets us create a data task that takes a URL and a closure (completion block in Objective-C) as an argument. Your closure will get the HTTP response, the Data/NSData returned by the server, and an error (if there was one) as arguments. We check to see if the error exists, and if it does not, we create a string from the Data and print it out. Be sure to call resume on the task to initiate the HTTP Request - this step is easily forgotten. 

Loading Code Samples...
Language
NSString* functionURL = @"https://yourdomain.twil.io/joke";
NSURL *url = [NSURL URLWithString:functionURL];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (error) {
        NSLog(@"Error: %@",error);
    } else {
        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Response: %@", responseString);
    }
}];
[task resume];
let functionURL = "https://yourdomain.twil.io/joke"
if let url = URL(string: functionURL) {
    let task = URLSession.shared.dataTask(with: url) {
        data, response, error in
        if error != nil {
            print(error!)
        } else {
            if let responseString = String(data: data!, encoding: .utf8) {
                print(responseString)
            }
        }
    }
    task.resume()
}
Call a Twilio Function from iOS

If you are calling Twilio Functions from an Xcode Playground with Swift, you will need to tell the Playground to run indefinitely (so the HTTP call can return).

To do this, you will need to import the PlaygroundSupport framework, and then include this line of code at the bottom:

PlaygroundPage.current.needsIndefiniteExecution = true

 

Return JSON from a Twilio Function

Our previous example Twilio Function returned plain text. You can easily return JSON from a Twilio Function, by passing a Javascript object or array to the callback function. For instance, we can create another Twilio Function to return a list of jokes, along with an id and a favorite count. I used the /jokes path for the new function. 

Jokes Twilio Function

 

Loading Code Samples...
Language
SDK Version:
  • 3.x
exports.handler = function(context, event, callback) {
  const knockKnock = { id: 1, text: 'Knock, knock', favorited: 37 };
  const chicken = {
    id: 2,
    text: 'Why did the chicken cross the road?',
    favorited: 12,
  };
  const jokes = [knockKnock, chicken];
  callback(null, jokes);
};
Demonstrate a Twilio Function that Returns a JSON Array

Parse JSON from a Twilio Function

From iOS, we call this Twilio Function the same way that we did our first Twilio Function (don't forget to change the path to /jokes). Instead of creating a String/NSString from data, we will use iOS's built-in JSON Serialization to parse the response data into an array. 

Loading Code Samples...
Language
NSString* functionURL = @"https://yourdomain.twil.io/jokes";
NSURL *url = [NSURL URLWithString:functionURL];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (error) {
        NSLog(@"Error: %@",error);
    } else {
        NSError *error;
        id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        NSLog(@"Response: %@", responseObject);
    }
}];
[task resume];
let functionURL = "https://yourdomain.twil.io/jokes"
if let url = URL(string: functionURL) {
    let task = URLSession.shared.dataTask(with: url) {
        data, response, error in
        if error != nil {
            print(error!)
        } else {
            do {
                let responseObject = try JSONSerialization.jsonObject(with: data!) as! [[String:Any]]
                print(responseObject)
            } catch let error as NSError {
                print(error)
            }
        }
    }
    task.resume()
}
Call a Twilio Function that returns JSON from iOS

Now you can see how easy it is to run Node.js code as a Twilio Function, and how your mobile application can use a serverless backend to provide data for your application. 

Where to go next? You could extend the Twilio Function to choose a random joke from that array. You can also use Twilio functionality from inside of your function, for instance to send an SMS, or to return an access token for Video, Chat, or Sync. Check out the Programmable SMS Quickstart for Twilio Functions and Programmable Voice Quickstart for Twilio Functions for a quick intro to Functions. Our documentation for Functions is also avaiable, if you have questions about how to debug your function.

Jeff Linwood
Kat King

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
SDK Version:
  • 3.x
exports.handler = function(context, event, callback) {
  const joke = 'How many apples grow on a tree? They all do!';
  callback(null, joke);
};
NSString* functionURL = @"https://yourdomain.twil.io/joke";
NSURL *url = [NSURL URLWithString:functionURL];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (error) {
        NSLog(@"Error: %@",error);
    } else {
        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Response: %@", responseString);
    }
}];
[task resume];
let functionURL = "https://yourdomain.twil.io/joke"
if let url = URL(string: functionURL) {
    let task = URLSession.shared.dataTask(with: url) {
        data, response, error in
        if error != nil {
            print(error!)
        } else {
            if let responseString = String(data: data!, encoding: .utf8) {
                print(responseString)
            }
        }
    }
    task.resume()
}
SDK Version:
  • 3.x
exports.handler = function(context, event, callback) {
  const knockKnock = { id: 1, text: 'Knock, knock', favorited: 37 };
  const chicken = {
    id: 2,
    text: 'Why did the chicken cross the road?',
    favorited: 12,
  };
  const jokes = [knockKnock, chicken];
  callback(null, jokes);
};
NSString* functionURL = @"https://yourdomain.twil.io/jokes";
NSURL *url = [NSURL URLWithString:functionURL];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (error) {
        NSLog(@"Error: %@",error);
    } else {
        NSError *error;
        id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        NSLog(@"Response: %@", responseObject);
    }
}];
[task resume];
let functionURL = "https://yourdomain.twil.io/jokes"
if let url = URL(string: functionURL) {
    let task = URLSession.shared.dataTask(with: url) {
        data, response, error in
        if error != nil {
            print(error!)
        } else {
            do {
                let responseObject = try JSONSerialization.jsonObject(with: data!) as! [[String:Any]]
                print(responseObject)
            } catch let error as NSError {
                print(error)
            }
        }
    }
    task.resume()
}