How to send text messages using the Twilio API on Mac OS X and iPhone

You may never have heard of Twilio, but odds are good that you use a product powered by their software. Twilio lets you send text messages and make phone calls using their API. They take care of all the details of working with the phone carriers and abstract it into an easy to use API.

Twilio has a variety of ways to use their services and the easiest one to use on the Mac/iPhone is their REST API. This lets you make a simple network request and send a text message. Here is how you use it.

The docs for sending an SMS message using the REST API can be found here. The message sending API takes three parameters.

To: The phone number the message will go to.
From: The phone number the message is from (if you use the Twilio sandbox number, you’ll need to verify any phone number you want to send a message).
Body: The body of the text message. (160 character maximum).

There are some optional callback parameters as well, but they aren’t too useful since Twilio can’t POST to a native app.

https://api.twilio.com/2010-04-01/Accounts/YOUR_ACCOUNT_SID_HERE/SMS/Messages is the URL you will be sending the request to.

The API uses HTTP basic authentication. Your account SID is the username and your auth token is the password.

__block ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.twilio.com/2010-04-01/Accounts/%@/SMS/Messages.json", accountSID]]] autorelease];

[request setUsername:accountSID];
[request setPassword:authToken];

[request addPostValue:fromNumber forKey:@"From"];
[request addPostValue:phoneNumber forKey:@"To"];
[request addPostValue:textToSend forKey:@"Body"];

[request setCompletionBlock:^(){
   NSLog(@"%@",request.responseString);

}];

[request setFailedBlock:^(){
   NSLog(@"%@", request.error);
}];

[request startAsynchronous];

The response you’ll get back is a bunch of information about the message that was sent, including a unique identifier for the message.

I put this together into an easy to use class called Twilinator and put it on GitHub. The project is for OS X but it doesn’t use anything that won’t work on iOS. It is very simple right now and just gives you a dictionary representing the message, after the message is sent to the Twilio servers.

This entry was posted in Uncategorized. Bookmark the permalink.

One Response to How to send text messages using the Twilio API on Mac OS X and iPhone

  1. Mark Uppaluri says:

    Elegant implementation. I made minor changes to leverage NSJSONSerializer (iOS5+). Thanks.

    //
    // Twilinator.m
    // Twilio
    //
    // Created by Randall Brown on 10/4/11.
    // Copyright 2011 __MyCompanyName__. All rights reserved.
    // Added To 2012 by Mark Uppaluri
    //

    #import “Twilinator.h”
    #import “ASIFormDataRequest.h”

    @implementation Twilinator

    – (id)initWithSID:(NSString*)sid authToken:(NSString*)theAuthToken fromNumber:(NSString*)number
    {
    self = [super init];
    if (self) {
    accountSID = [sid retain];
    authToken = [theAuthToken retain];
    fromNumber = [number retain];
    }

    return self;

    }

    -(void)dealloc
    {
    [accountSID release];
    [authToken release];
    [fromNumber release];
    [super dealloc];
    }

    -(void)sendTextMessage:(NSString*)textToSend toPhoneNumber:(NSString*)phoneNumber completionHandler:(void (^)(NSDictionary *responseDictionary, NSError *error))handler;
    {
    __block ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@”https://api.twilio.com/2010-04-01/Accounts/%@/SMS/Messages.json”, accountSID]]] autorelease];

    [request setUsername:accountSID];
    [request setPassword:authToken];

    [request addPostValue:fromNumber forKey:@”From”];
    [request addPostValue:phoneNumber forKey:@”To”];
    [request addPostValue:textToSend forKey:@”Body”];

    [request setCompletionBlock:^(){
    NSData *response = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:response options:0 error:nil];
    handler( responseDict, nil );

    }];

    [request setFailedBlock:^(){
    handler( nil, request.error );
    }];

    [request startAsynchronous];
    }

    @end

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>