我怎样才能send SMS through 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。 请帮助解决这个问题,或与我分享任何帮助材料。在此先感谢。
答案 0 :(得分:4)
根据this answer,错误1012表示用户取消了身份验证请求。
这只是一种预感,但您可能想尝试使用HTTP Basic Auth,方法是添加如下所示的Authorization标头:Objective-c HTTP Basic authentication而不是在URL字符串中包含凭据,这些凭据依赖于Objective C库来转向那些正确的标题。
答案 1 :(得分:4)
确保HttpPost参数是URL编码的,因此您应该更改
NSString *kToNumber = @"+14126620408";
到
NSString *kToNumber = @"%2B14126620408";
答案 2 :(得分:0)
我写了这篇博文,帮助您使用Xcode 8和Swift 3快速完成这项工作。
https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html
使用您选择的服务器端语言和Alamofire进行HTTP请求,请求可归结为:
@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)
}
}
答案 3 :(得分:0)
@IBAction func sendData(sender: AnyObject) { 让标题 = [ “内容类型”:“应用程序/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)
}
}
你必须安装 提示:pod 'Alamofire', '~> 5.2'