Send SMS from Twilio to Swift

I am trying to use Twilio as a service provider, but they have no examples for Swift that I understand.

My task is to send SMS to a number using the Twilio API with Swift.

I have a Twilio.com account - and it works. But how to do it in Swift code is easy.

Twilio does provide a library, but this is for C # not Swift (and using the bridge header seems too complicated!)

Here is a C # example, I need a simple Swift example.

// 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); } } 
+7
ios swift twilio
source share
6 answers

Twilio the evangelist is here.

To send a text message from Swift, you can simply send the request directly to the Twilios REST API. However, I do not recommend doing this from an iOS application (or any other client application), as it requires you to paste your credentials into Twilio into the application, which is dangerous. Instead, I would recommend sending SMS messages from the server-side application.

If you want to send a message from your application, there are several Swift libraries that I know of that make it easy to create HTTP requests:

To make a request using SwiftRequest, it will look like this:

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

Hope this helps.

+7
source share

I recently went through Twilio docs and a few SO posts.

you can send SMS using the following code in 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() } 

If everything will be ok. You should receive such a message.

enter image description here

+5
source share

Here is a new Swift example for passwordless authentication. For a complete tutorial 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"); } }) 
0
source share

If you are using Swift backend with Perfect.org View this blog http://perfecttwilio.blogspot.in

0
source share

The answer "Devin Rader" is perfect. For any other users like me, the complete code for SwiftRequest for Swift 3.0 is provided. The original code is Ricky Robint.

Please let us know if any errors have occurred.

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 } } 

Sample code for using the above class mentioned in "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))") } }); 
0
source share

Swift 3 version:

 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() } 
0
source share

All Articles