5

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:bf...0b7@api.twilio.com/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);
Steven Hepting
  • 12,394
  • 8
  • 40
  • 50
  • I think the problem is that you should be using POST fields, not HTTP Headers... I'll verify that real quick... – Andrew Watson Jul 26 '11 at 16:16
  • Please be aware that using the Twilio API to send text messages directly from an iOS application is not recommended because you have to embed your AccountSid and AuthToken in the app, which can be easily decompiled compromising your credentials. Its much more secure to use a service like Parse or Azure Mobile Services to host a simple service that sends the message and just call that from your app. – Devin Rader Aug 29 '13 at 18:48
  • Devin, even with Parse or Azure you will have to put your authorization token into your compiled app. – Steven Hepting Oct 05 '15 at 22:28
  • Meaning of queued ? I get this in response. – Pramod Tapaniya Mar 18 '16 at 09:31

5 Answers5

16

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

Steven Hepting
  • 12,394
  • 8
  • 40
  • 50
  • I am using Your code to send SMS in iOS application. But i am getting a different error than you while sending the SMS. The 'To' number +91********** is not a valid phone number(Code 21211) I have checked that the number i am using is properly defined with +(Country Code)(Phone No). Can you help me in this problem? – – Rachit Aug 20 '13 at 12:42
  • 1
    NSString *kToNumber = @"+14126620408"; change to NSString *kToNumber = @"%2B14126620408"; similarly for from. – Ankish Jain Jun 08 '15 at 12:37
  • Thanks! that really saved my time. – ZaEeM ZaFaR Mar 17 '16 at 07:01
  • @steven hepting Meaning of queued ? I get this in response. – Pramod Tapaniya Mar 18 '16 at 09:25
  • @PramodTapaniya That just means that the Twilio server has correctly received your request to send the text message and that they will talk to the carrier network on your behalf to make sure that the SMS is sent. – Steven Hepting Mar 18 '16 at 19:52
  • @StevenHepting but till now not receive any message. – Pramod Tapaniya Mar 19 '16 at 03:58
  • @StevenHepting why not receive messages on my mobile phone. – Pramod Tapaniya Mar 19 '16 at 03:59
2

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]];
    }];
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Iya
  • 1,888
  • 19
  • 12
0

It could be this:

The number +YOURNUMBER is unverified. Trial accounts cannot send messages to unverified numbers; verify +YOURNUMBER at twilio.com/user/account/phone-numbers/verified, or purchase a Twilio number to send messages to unverified numbers.

Isuru
  • 30,617
  • 60
  • 187
  • 303
atkinja
  • 11
  • 2
0

Twilio with Swift 2.2+, Alamofire, SwiftyJSON -> answer:

import Alamofire
import SwiftyJSON
........
........
//twillio config
private static let TWILIO_ACCOUNT_SID = "A...7"
private static let TWILIO_AUTH_TOKEN = "6...5"
//end url string is .json,to get response as JSON
static let URL_TWILIO_SMS = "https://\(TWILIO_ACCOUNT_SID):\(TWILIO_AUTH_TOKEN)@api.twilio.com/2010-04-01/Accounts/\(TWILIO_ACCOUNT_SID)/SMS/Messages.json"


Alamofire.request(.POST, URL_TWILIO_SMS, parameters: ["To":"+880....6","From":"+1...9","Body":"Hellow Rafsun"])


        .responseJSON { response in

            if let jso = response.result.value {

                let json = JSON(jso)

                //Twilio response
                if let twStatus = json["status"].string,twSentMessage = json["body"].string where twStatus == "queued"{
                //Twilio message sent
                }else{
                //Twilio message not sent
                }

            }else if let error = response.result.error?.localizedDescription{
                //parse error
            }
    }
Rafat touqir Rafsun
  • 2,777
  • 28
  • 24
0

An example (updated) for Xcode 8 and Swift 3.

https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html

We don't recommend storing your credentials client side and so the post shows you how to avoid a potential vulnerability using a server-side language of your choosing and Alamofire for HTTP requests:

@IBAction func sendData(sender: AnyObject) { 
    let headers = [
        "Content-Type": "application/x-www-form-urlencoded"
    ]

    let parameters: Parameters = [
        "To": phoneNumberField.text ?? "",
        "Body": messageField.text ?? ""
    ]

    Alamofire.request("YOUR_NGROK_URL/sms", method: .post, parameters: parameters, headers: headers).response { response in
            print(response)

    }
}
Megan Speir
  • 3,745
  • 1
  • 15
  • 25