5

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

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

我当前的代码是通过简单的按钮按下调用的方法。

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

5 回答 5

16

MFMessageComposeViewController如果您只是想在 iOS中发送 SMS 消息,您可以使用MessageUI.framework. 如您所知,这需要用户交互。

正如您所要求的,您可以使用 Twilio 在几乎任何平台上直接发送 SMS。对于 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

于 2011-07-26T22:28:57.647 回答
2

使用 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]];
    }];
于 2015-09-27T09:04:59.593 回答
0

可能是这样的:

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

于 2013-08-29T07:51:07.347 回答
0

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)

    }
}
于 2016-11-03T20:07:41.560 回答
0

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
            }
    }
于 2016-07-14T08:22:49.757 回答