Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send SMS Message with Twilio on iOS

How can I send an SMS message programatically from an iPhone app? I'm using Twilio right now, and can correctly set up a HTTP Request, authenticate with the server, and get a response.

There must be some misconfiguration of the HTTP Headers as I can get a response from the Twilio servers but never passes the right data through.

My current code is in a method that's called by a simple button press.

- (IBAction)sendButtonPressed:(id)sender {
 NSLog(@"Button pressed.");

 NSString *kYourTwillioSID = @"AC8c3...f6da3";
 NSString *urlString = [NSString stringWithFormat:@"https://AC8c3...6da3:[email protected]/2010-04-01/Accounts/%@/SMS/Messages", kYourTwillioSID];
 NSURL *url = [NSURL URLWithString:urlString];
 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
 [request setURL:url];
 [request setValue:@"+18584334333" forHTTPHeaderField:@"From"];
 [request setValue:@"+13063707780" forHTTPHeaderField:@"To"];
 [request setValue:@"Hello\n" forHTTPHeaderField:@"Body"];

 NSError *error;
 NSURLResponse *response;
 NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

 if (!error) {
    NSString *response_details = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",response_details);

 }
 NSLog(@"Request finished %@", error);
like image 778
Steven Hepting Avatar asked Jul 26 '11 15:07

Steven Hepting


People also ask

How do I send an SMS with Twilio's API?

Send an SMS with Twilio's API. To send a new outgoing message from a Twilio phone number to an outside number, make an HTTP POST to your account's Message resource: You can post directly to the API with cURL or use one of our six supported helper libraries to send messages with C#, Java, Node.js, PHP, Python or Ruby.

How do I format a phone number in the Twilio API?

Format this number with a '+' and a country code, e.g., +16175551212 ( E.164 format ). If you send messages while in trial mode, you must first verify your 'To' phone number so Twilio knows you own it. If you attempt to send an SMS from your trial account to an unverified number, the API will return Error 21219.

Does Twilio affect my phone or carrier?

This behavior is controlled from the phone or its software, and can not be affected by Twilio or the carrier. The SMS and MMS protocols were created prior to smartphones or mobile internet use becoming common, and specifications for handling URL and link previews were not included.

What parameters does Twilio send to my callback url?

The parameters Twilio sends to your callback URL include a subset of the standard request parameters and some unique messaging parameters. You can see the full list in the API Reference for the Message resource. Below is an example of the request parameters sent to the StatusCallback URL for a delivered message:


2 Answers

If you are just looking to send an SMS message in iOS you can use the MFMessageComposeViewController inside of the MessageUI.framework. As you know though, this requires user-interaction.

As you had requested, you can use Twilio to send SMS directly using almost any platform. For iOS you can use the following Swift code to hit the Twilio API and send any text messages you'd like:

func tappedSendButton() {
    print("Tapped button")

    // Use your own details here
    let twilioSID = "AC8c3...6da3"
    let twilioSecret = "bf2...b0b7"
    let fromNumber = "4152226666"
    let toNumber = "4153338888"
    let message = "Hey"

    // Build the request
    let request = NSMutableURLRequest(URL: NSURL(string:"https://\(twilioSID):\(twilioSecret)@api.twilio.com/2010-04-01/Accounts/\(twilioSID)/SMS/Messages")!)
    request.HTTPMethod = "POST"
    request.HTTPBody = "From=\(fromNumber)&To=\(toNumber)&Body=\(message)".dataUsingEncoding(NSUTF8StringEncoding)

    // Build the completion block and send the request
    NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in
        print("Finished")
        if let data = data, responseDetails = NSString(data: data, encoding: NSUTF8StringEncoding) {
            // Success 
            print("Response: \(responseDetails)")
        } else {
            // Failure
            print("Error: \(error)")
        }
    }).resume()

For any further API interaction you can check out the official docs: https://www.twilio.com/docs/api/rest

like image 169
Steven Hepting Avatar answered Oct 18 '22 16:10

Steven Hepting


Use AFNetworking to send request.

NSString *kTwilioSID = @"AC73bb270.......4d418cb8";
NSString *kTwilioSecret = @"335199.....9";
NSString *kFromNumber = @"+1......1";
NSString *kToNumber = @"+91.......8";
NSString *kMessage = @"Hi";

NSString *urlString = [NSString
stringWithFormat:@"https://%@:%@@api.twilio.com/2010-04-01/Accounts/%@/SMS/Messages/",
kTwilioSID, kTwilioSecret,kTwilioSID];

NSDictionary*
dic=@{@"From":kFromNumber,@"To":kToNumber,@"Body":kMessage};

__block NSArray* jsonArray;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"application/xml"];
[manager POST:urlString parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSError* err;
        NSLog(@"success %@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
        jsonArray=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments
error:&err];
        [_del getJsonResponsePOST:jsonArray];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        [_del getError:[NSString stringWithFormat:@"%@",error]];
    }];
like image 25
Iya Avatar answered Oct 18 '22 14:10

Iya