如何以编程方式从iPhone应用程序发送短信?我现在正在使用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);
答案 0 :(得分:16)
如果您只是想在iOS中发送短信,可以使用MFMessageComposeViewController
内的MessageUI.framework
。如您所知,这需要用户互动。
根据您的要求,您可以使用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
答案 1 :(得分:3)
好的,我认为标题是对的。
我发现这个答案似乎证实了这一点:iOS: how to perform a HTTP POST request?
您必须在请求正文中发送POST数据,而不是在标头中。 Twilio正在进行HTTP调用,但POST数据为空。
如果有效,请告诉我。
答案 2 :(得分: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]];
}];
答案 3 :(得分:0)
可能是这样的:
号码+ YOURNUMBER未经验证。试用帐户无法向未经验证的号码发送邮件;在twilio.com/user/account/phone-numbers/verified验证+ YOURNUMBER,或购买Twilio号码以向未经验证的号码发送消息。
答案 4 :(得分:0)
Twilio, Swift 2.2 + , Alamofire , SwiftyJSON - >回答:
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
}
}
答案 5 :(得分:0)
Xcode 8和 Swift 3 的示例(已更新)。
https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html
我们不建议您存储您的凭据客户端,因此该帖子向您展示了如何使用您选择的服务器端语言和 Alamofire 来避免潜在的漏洞:< / p>
@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)
}
}