在Swift中使用Twilio发送短信

时间:2014-12-09 19:11:03

标签: ios swift twilio

我尝试使用Twilio作为服务提供者,但他们没有我理解的Swift示例。

我的任务是使用Swift的Twilio API向一个号码发送短信。

我有一个Twilio.com帐户 - 那个工作正常。但是我如何以简单的方式在Swift代码中执行此操作。

Twilio确实提供了一个库 - 但这适用于C#而不是Swift(并且使用桥接头看起来太复杂了!)

这是C#示例,我需要一个简单的Swift示例。

// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio;
class Example 
{
  static void Main(string[] args) 
  {
    // Find your Account Sid and Auth Token at twilio.com/user/account
    string AccountSid = "AC5ef8732a3c49700934481addd5ce1659";
    string AuthToken = "{{ auth_token }}";
    var twilio = new TwilioRestClient(AccountSid, AuthToken);


    var message = twilio.SendMessage("+14158141829", "+15558675309", "Jenny please?! I love you <3", new string[] {"http://www.example.com/hearts.png"});

    Console.WriteLine(message.Sid);
  }
}

6 个答案:

答案 0 :(得分:9)

Twilio传道者在这里。

要从Swift发送文本消息,您只需直接向Twilios REST API发出请求即可。也就是说,我不会建议从iOS应用程序(或任何其他客户端应用程序)执行此操作,因为它要求您在应用程序中嵌入Twilio帐户凭据,这很危险。我建议从服务器端应用程序发送SMS。

如果您确实想从您的应用程序发送消息,我知道有几个Swift库可以简化HTTP请求:

要使用SwiftRequest发出请求,它看起来像这样:

var swiftRequest = SwiftRequest();

var data = [
    "To" : "+15555555555",
    "From" : "+15555556666",
    "Body" : "Hello World"
];

swiftRequest.post("https://api.twilio.com/2010-04-01/Accounts/[YOUR_ACCOUNT_SID]/Messages", 
    auth: ["username" : "[YOUR_ACCOUNT_SID]", "password" : "YOUR_AUTH_TOKEN"]
    data: data, 
    callback: {err, response, body in
        if err == nil {
            println("Success: \(response)")
        } else {
            println("Error: \(err)")
        }
});

希望有所帮助。

答案 1 :(得分:5)

最近我通过了Twilio文档和很少的帖子。

  

您可以在Swift 2.0中使用以下代码段发送短信

func sendSMS()
    {

        let twilioSID = "your Sender ID here"
        let twilioSecret = "your token id here"

        //Note replace + = %2B , for To and From phone number
        let fromNumber = "%2B14806794445"// actual number is +14803606445
        let toNumber = "%2B919152346132"// actual number is +919152346132
        let message = "Your verification code is 2212 for signup with <app name here> "

        // 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()
}

如果一切顺利......你应该收到这样的消息..

enter image description here

答案 2 :(得分:0)

以下是无密码身份验证的新Swift示例。有关完整教程Click Here

let url = "http://localhost:8000"
  var swiftRequest = SwiftRequest()
  var params:[String:String] = [
    "token" : token!.text
  ]

  swiftRequest.post(url + "/user/auth/", data: params, callback: {err, response, body in
    if( err == nil && response!.statusCode == 200) {
      if((body as NSDictionary)["success"] as Int == 1) {
        self.showAlert("User successfully authenticated!");
      } else {
        self.showAlert("That token isn't valid");
      }
    } else {
      self.showAlert("We're sorry, something went wrong");
    }
  })

答案 3 :(得分:0)

如果您正在使用服务器端Swift和Perfect.org 看到这个博客 http://perfecttwilio.blogspot.in

答案 4 :(得分:0)

“Devin Rader”的答案是完美的。对于像我这样的任何其他用户,以下是SwiftRequest for swift 3.0的完整转换代码。原始代码由Ricky Robinett提供。

如果有任何错误,请告诉我们。

Thankx ..

//
//  SwiftRequest.swift
//  SwiftRequestTest
//
//  Created by Ricky Robinett on 6/20/14.
//  Copyright (c) 2015 Ricky Robinett. All rights reserved.
//
// ***********************************************************
//
// Modification for Swift 3.0 by Sanjay Sampat on 21.Jun.2017
//
// ***********************************************************

import Foundation

public class SwiftRequest {
    var session = URLSession.shared

    public init() {
        // we should probably be preparing something here...
    }

    // GET requests
    public func get(url: String, auth: [String: String] = [String: String](), params: [String: String] = [String: String](), callback: ((_ err: NSError?, _ response: HTTPURLResponse?, _ body: AnyObject?)->())? = nil) {
        let qs = dictToQueryString(data: params)
        request(options: ["url" : url, "auth" : auth, "querystring": qs ], callback: callback )
    }

    // POST requests
    public func post(url: String, data: [String: String] = [String: String](), auth: [String: String] = [String: String](), callback: ((_ err: NSError?, _ response: HTTPURLResponse?, _ body: AnyObject?)->())? = nil) {
        let qs = dictToQueryString(data: data)
        request(options: ["url": url, "method" : "POST", "body" : qs, "auth" : auth] , callback: callback)
    }

    // Actually make the request
    func request(options: [String: Any], callback: ((_ err: NSError?, _ response: HTTPURLResponse?, _ body: AnyObject?)->())?) {
        if( options["url"] == nil ) { return }

        var urlString = options["url"] as! String
        if( options["querystring"] != nil && (options["querystring"] as! String) != "" ) {
            let qs = options["querystring"] as! String
            urlString = "\(urlString)?\(qs)"
        }

        let url = NSURL(string:urlString)
        let urlRequest = NSMutableURLRequest(url: url! as URL)

        if( options["method"] != nil) {
            urlRequest.httpMethod = options["method"] as! String
        }

        if( options["body"] != nil && options["body"] as! String != "" ) {
            var postData = (options["body"] as! String).data(using: String.Encoding.ascii, allowLossyConversion: true)
            urlRequest.httpBody = postData
            urlRequest.setValue("\(postData!.count)", forHTTPHeaderField: "Content-length")
        }

        // is there a more efficient way to do this?
        if( options["auth"] != nil && (options["auth"] as! [String: String]).count > 0) {
            var auth = options["auth"] as! [String: String]
            if( auth["username"] != nil && auth["password"] != nil ) {
                let username = auth["username"]
                let password = auth["password"]
                var authorization = "\(username!):\(password!)"
                if let data = authorization.data(using: String.Encoding.utf8) {
                    //authorization = "Basic " + data.base64EncodedString(options: [])
                    authorization = "Basic " + data.base64EncodedString()
                }

                urlRequest.setValue(authorization, forHTTPHeaderField: "Authorization")
            }
        }

        let task = session.dataTask(with: urlRequest as URLRequest, completionHandler: {body, response, err in
            let resp = response as! HTTPURLResponse?

            if( err == nil) {
                if let gotResponse = response {
                if(gotResponse.mimeType == "text/html") {
                    let bodyStr = NSString(data: body!, encoding:String.Encoding.utf8.rawValue)
                    return callback!(err as NSError?, resp, bodyStr)
                } else if(gotResponse.mimeType == "application/xml") {
                    let bodyStr = NSString(data: body!, encoding:String.Encoding.utf8.rawValue)
                    return callback!(err as NSError?, resp, bodyStr)
                } else if(gotResponse.mimeType == "application/json") {
                    // ss pending
                    do {
                        let jsonAnyObject:AnyObject = try JSONSerialization.jsonObject(with: (body! as NSData) as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject] as AnyObject
                        return callback!(err as NSError?, resp, jsonAnyObject as AnyObject);
                    } catch _ {
                    }
                }
            }
            }

            return callback!(err as NSError?, resp, body as AnyObject)
        })

        task.resume()
    }

    func request(url: String, callback: ((_ err: NSError?, _ response: HTTPURLResponse?, _ body: AnyObject?)->())? = nil) {
        request(options: ["url" : url ], callback: callback )
    }

    private func dictToQueryString(data: [String: String]) -> String {

        var qs = ""
        for (key, value) in data {
            let encodedKey = encode(value: key)
            let encodedValue = encode(value: value)
            qs += "\(encodedKey)=\(encodedValue)&"
        }
        return qs
    }

    private func encode(value: String) -> String {

        let queryCharacters =  NSCharacterSet(charactersIn:" =\"#%/<>?@\\^`{}[]|&+").inverted

        if let encodedValue:String = value.addingPercentEncoding(withAllowedCharacters: queryCharacters) {
            return encodedValue
        }

        //let encodedValue:String = value.stringByAddingPercentEncodingWithAllowedCharacters(queryCharacters)!

        return value
    }
}

“Devin Rader”提到的上面使用的示例代码

    let URL = "https://api.twilio.com/2010-04-01/Accounts/\(myUserIdForBulkSmsMessageSending)/Messages"         
    var swiftRequest = SwiftRequest();

    var data = [
        "To" : "+\(replaceNumberToSendSms)",
        "From" : "+\(replaceNumberFromSendSms)",
        "Body" : message,
        "MediaUrl" : theUrlEncodedMessage
    ];
    //print( "=========VV==========" )
    //print( "URL: \(URL) " )
    //print( "data: \(String(describing: data))" )
    //print( "auth: \(myUserIdForBulkSmsMessageSending)   \(myUserPasswordForBulkSmsMessageSending)")
    //print( "=====================" )
    swiftRequest.post(url: URL,
                      data: data,
                      auth: ["username" : myUserIdForBulkSmsMessageSending, "password" : myUserPasswordForBulkSmsMessageSending],
        callback: {err, response, body in
            if err == nil {
                print("Success: \(String(describing: response))")
                if let currentBody = body {

                    // SSTODO PENDING TO HANDLE SUCCESS OF TWILLO OR ERRORS HANDLING OF TWILLO.

                    //print( "=====================" )
                    //print( " currentBody:  \(currentBody) " )
                    //print( " currentBodyString: \(String(describing: currentBody)) ")
                    //print( "=========^^==========" )
                }
            } else {
                print("Error: \(String(describing: err))")
            }
    });

答案 5 :(得分:0)

Swift 3版本:

func sendSMS()
{
    print("Starting...")
    let twilioSID = "ENRET YOUR SID"
    let twilioSecret = "YOUR TOKEN"
    //Note replace + = %2B , for To and From phone number
    let fromNumber = "%29999999"// actual number is +9999999
    let toNumber = "%29999999"// actual number is +9999999
    let message = "Your verification code is 2212 for signup with"

    // Build the request
    let request = NSMutableURLRequest(url: URL(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)".data(using: .utf8)

    // Build the completion block and send the request
    URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
        print("Finished")
        if let data = data, let responseDetails = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
            // Success
            print("Response: \(responseDetails)")
        } else {
            // Failure
            print("Error: \(error)")
        }
    }).resume()
}