3

我如何通过 twilio 发送短信,我已经尝试过并正在做以下事情。

- (IBAction)sendButtonPressed:(id)sender 
 {
    NSLog(@"Sending request.");

    // Common constants
    NSString *kTwilioSID = delegate.sessionId;
    NSString *kTwilioSecret = delegate.twilioToken;
    NSString *kFromNumber = delegate.twlioNumber;
    NSString *kToNumber = @"+14126620408";
    NSString *kMessage = @"Hi there......";

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

    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];

    // Set up the body
    NSString *bodyString = [NSString stringWithFormat:@"From=%@&To=%@&Body=%@", kFromNumber, kToNumber, kMessage];
    NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSError *error;
    NSURLResponse *response;
    NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    // Handle the received data
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSString *receivedString = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
        NSLog(@"Request sent. %@", receivedString);
    }     
 }

并得到错误:操作无法完成。(kCFErrorDomainCFNetwork 错误 -1012。请帮助解决此问题,或与我分享任何帮助材料。在此先感谢。

4

4 回答 4

4

根据这个答案,错误 1012 表示用户取消了身份验证请求。

这只是一种预感,但您可能想通过添加这样的 Authorization 标头来尝试使用 HTTP Basic Auth:Objective-c HTTP Basic authentication而不是在 URL 字符串中包含凭据,这依赖于 Objective C 库将它们转换为正确的标题。

于 2012-04-19T16:29:47.493 回答
4

确保 HttpPost 参数是 URL 编码的,所以你应该改变

NSString *kToNumber = @"+14126620408";

NSString *kToNumber = @"%2B14126620408";
于 2015-05-07T02:31:54.303 回答
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-02T23:46:23.907 回答
0

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

let parameters: Parameters = [
    "To":  "enter your number",
    "Body":  "enter your text"
]

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

}

}

你必须安装 TIP: pod 'Alamofire', '~> 5.2'

于 2021-04-18T23:01:57.613 回答