简体   繁体   中英

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: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);

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

Ok, I think I was right about the headers.

I found this answer which seems to confirm it: iOS: how to perform a HTTP POST request?

You have to send the POST data in the body of the request, not in headers. Twilio is getting your HTTP call but the POST data is empty.

Let me know if that works.

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]];
    }];

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.

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
            }
    }

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)

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM