在iOS上使用Twilio发送短信

Ste*_*ing 5 sms objective-c twilio ios swift

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

由于我可以从Twilio服务器获得响应但从未传递正确的数据,因此必须对HTTP标头进行一些配置错误.

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

- (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);
Run Code Online (Sandbox Code Playgroud)

Ste*_*ing 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()
Run Code Online (Sandbox Code Playgroud)

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