Enviar SMS con Twilio en Swift

Trato de usar Twilio como proveedor de services, pero no tienen ejemplos para Swift que entiendo.

Mi tarea es enviar SMS a un número utilizando Twilio API con Swift.

Tengo una count de Twilio.com, y esa está funcionando. Pero, ¿cómo hago esto en el código Swift de una manera fácil?

Twilio proporciona una biblioteca, pero para C # no es para Swift (¡y usar un encabezado de puente parece demasiado complicado!)

Aquí está el ejemplo de C #, necesito un ejemplo de Swift fácil.

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

Evangelist de Twilio aquí

Para enviar un post de text desde Swift, puede hacer una request directamente a Twilios REST API. Dicho esto, no recomendaría hacerlo desde una aplicación de iOS (o cualquier otra aplicación de cliente), ya que requiere que incruste las cnetworkingenciales de su count Twilio en la aplicación, lo cual es peligroso. En su lugar, recomendaría enviar los SMS desde una aplicación del lado del server.

Si desea enviar el post desde su aplicación, hay un par de bibliotecas Swift que conozco que simplifican la creación de requestes HTTP:

Para realizar la request utilizando SwiftRequest, se vería así:

 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)") } }); 

Espero que ayude.

Recientemente he revisado los documentos de Twilio y algunas publicaciones SO.

puede enviar SMS con el siguiente código de snip en 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.shanetworkingSession().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() } 

si todo va bien … Debes recibir un post como este …

introduzca la descripción de la imagen aquí

Aquí está el nuevo ejemplo de Swift para la authentication sin contraseña. Para el tutorial completo, haga clic aquí

 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"); } }) 

Si está utilizando Swift del lado del server con Perfect.org, consulte este blog http://perfecttwilio.blogspot.in

La respuesta de "Devin Rader" es perfecta. Para cualquier otro usuario como yo, el siguiente es el código convertido completo para SwiftRequest para swift 3.0. El código original es de Ricky Robinett.

Por favor, háganos saber si hay algún error.

Gracias …

 // // 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.shanetworking 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 } } 

Código de ejemplo para usar por encima de la class como lo menciona "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))") } }); 

Versión 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.shanetworking.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() }