在 iOS 上使用 Twilio 发送短信

发布于 2024-11-26 13:38:43 字数 1284 浏览 7 评论 0原文

如何从 iPhone 应用程序以编程方式发送 SMS 消息?我现在正在使用 Twilio,并且可以正确设置 HTTP 请求、向服务器进行身份验证并获取响应。

HTTP 标头肯定存在一些错误配置,因为我可以从 Twilio 服务器获取响应,但从未传递正确的数据。

我当前的代码位于通过简单按下按钮即可调用的方法中。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

余生一个溪 2024-12-03 13:38:43

如果您只是想在 iOS 中发送短信,您可以使用 MessageUI.framework 内的 MFMessageComposeViewController。但正如您所知,这需要用户交互。

正如您所要求的,您可以使用 Twilio 直接使用几乎任何平台发送短信。对于 iOS,您可以使用以下 Swift 代码来访问 Twilio API 并发送您想要的任何短信:

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()

对于任何进一步的 API 交互,您可以查看官方文档:https://www.twilio.com/docs/api/rest

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

信仰 2024-12-03 13:38:43

使用AFNetworking发送请求。

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

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]];
    }];
梦萦几度 2024-12-03 13:38:43

可能是这样的:

号码+YOURNUMBER 未经验证。试用账户无法向未经验证的号码发送消息;在twilio.com/user/account/phone-numbers/verified,或购买 Twilio 号码以向未经验证的号码发送消息。

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.

沉鱼一梦 2024-12-03 13:38:43

Twilio 与 Swift 2.2+AlamofireSwiftyJSON ->回答:

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

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
            }
    }
自此以后,行同陌路 2024-12-03 13:38:43

Xcode 8 和 Swift 3 的示例(已更新)。

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

我们不建议在客户端存储您的凭据,因此帖子展示如何使用您选择的服务器端语言和 HTTP 请求的 Alamofire 来避免潜在的漏洞:

@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)

    }
}

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)

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文