Expression resolves to an unused function (Swift) - ios

I am new to swift programming and need bit of your help forgive me if i am asking something stupid. I am trying call a function from my UIViewController for a POST request to API. Calling function is like this
#IBAction func actionStartSignIn(sender: AnyObject) {
let email: String = txtEmail.text!
let password: String = txtPassword.text!
if !email.isEmpty && !password.isEmpty && General.isValidEmail(email) && password.characters.count>6{
var request = RequestResponse()
request.email = email
request.password = password
let isValid = NSJSONSerialization.isValidJSONObject(request)
print(isValid)
var requestBody: String = ""
// Facing issue in following line
RequestManager.sharedInstance.postRequest(Constants.BASE_URL + Constants.LOGIN, body: requestBody, onCompletion: {(json: JSON) in{
let result = json["response"]
print(result)
}
}
)
}
}
And Called Function is like this
func postRequest(route: String, body: String, onCompletion: (JSON) -> Void) {
makeHTTPPostRequest(route, requestBody: body, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
Further,
// MARK: Perform a POST Request
private func makeHTTPPostRequest(path: String, requestBody: String, onCompletion: ServiceResponse) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
// Set the method to POST
request.HTTPMethod = "POST"
do {
// Set the POST body for the request
// let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted)
// request.HTTPBody = jsonBody
request.HTTPBody = requestBody.dataUsingEncoding(NSUTF8StringEncoding);
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
onCompletion(json, nil)
} else {
onCompletion(nil, error)
}
})
task.resume()
}/* catch {
// error
onCompletion(nil, nil)
}*/
}
and
typealias ServiceResponse = (JSON, NSError?) -> Void
I am facing "Expression resolves to an unused function" while calling
RequestManager.sharedInstance.postRequest(Constants.BA‌​SE_URL + Constants.LOGIN, body: requestBody, onCompletion: {(json: JSON) in{ let result = json["response"] print(result) } } )
May be i am missing some basic syntax. Any help will be really appreciated.
Thank You.

Remove the { } phase after the in will solve the problem.
It should look like this:
RequestManager.sharedInstance.postRequest(Constants.BASE_URL + Constants.LOGIN, body: requestBody, onCompletion: {(json: JSON) in
let result = json["response"]
print(result)
}
)
For the closure param, you should not type it by yourself to prevent typo. Use tab key to select that param, then press enter, xCode will auto generate the code for you.
If use the way I just said, the trailing closure will look like this:
RequestManager.sharedInstance.postRequest(Constants.BASE_URL + Constants.LOGIN, body: requestBody) { (json) in
let result = json["response"]
print(result)
}

Related

Codable for API request

How would I make this same API request through codables?
In my app, this function is repeated in every view that makes API calls.
func getOrders() {
DispatchQueue.main.async {
let spinningHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
spinningHUD.isUserInteractionEnabled = false
let returnAccessToken: String? = UserDefaults.standard.object(forKey: "accessToken") as? String
let access = returnAccessToken!
let headers = [
"postman-token": "dded3e97-77a5-5632-93b7-dec77d26ba99",
"Authorization": "JWT \(access)"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://somelink.com")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error!)
} else {
if let dataNew = data, let responseString = String(data: dataNew, encoding: .utf8) {
print("----- Orders -----")
print(responseString)
print("----------")
let dict = self.convertToDictionary(text: responseString)
print(dict?["results"] as Any)
guard let results = dict?["results"] as? NSArray else { return }
self.responseArray = (results) as! [HomeVCDataSource.JSONDictionary]
DispatchQueue.main.async {
spinningHUD.hide(animated: true)
self.tableView.reloadData()
}
}
}
})
dataTask.resume()
}
}
I would suggest to do the following
Create Base Service as below
import UIKit
import Foundation
enum MethodType: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
}
class BaseService {
var session: URLSession!
// MARK: Rebuilt Methods
func FireGenericRequest<ResponseModel: Codable>(url: String, methodType: MethodType, headers: [String: String]?, completion: #escaping ((ResponseModel?) -> Void)) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
// Request Preparation
guard let serviceUrl = URL(string: url) else {
print("Error Building URL Object")
return
}
var request = URLRequest(url: serviceUrl)
request.httpMethod = methodType.rawValue
// Header Preparation
if let header = headers {
for (key, value) in header {
request.setValue(value, forHTTPHeaderField: key)
}
}
// Firing the request
session = URLSession(configuration: URLSessionConfiguration.default)
session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
if let data = data {
do {
guard let object = try? JSONDecoder().decode(ResponseModel.self , from: data) else {
print("Error Decoding Response Model Object")
return
}
DispatchQueue.main.async {
completion(object)
}
}
}
}.resume()
}
private func buildGenericParameterFrom<RequestModel: Codable>(model: RequestModel?) -> [String : AnyObject]? {
var object: [String : AnyObject] = [String : AnyObject]()
do {
if let dataFromObject = try? JSONEncoder().encode(model) {
object = try JSONSerialization.jsonObject(with: dataFromObject, options: []) as! [String : AnyObject]
}
} catch (let error) {
print("\nError Encoding Parameter Model Object \n \(error.localizedDescription)\n")
}
return object
}
}
the above class you may reuse it in different scenarios adding request object to it and passing any class you would like as long as you are conforming to Coddle protocol
Create Model Conforming to Coddle protocol
class ExampleModel: Codable {
var commentId : String?
var content : String?
//if your JSON keys are different than your property name
enum CodingKeys: String, CodingKey {
case commentId = "CommentId"
case content = "Content"
}
}
Create Service to the specific model with the endpoint constants subclassing to BaseService as below
class ExampleModelService: BaseService<ExampleModel/* or [ExampleModel]*/> {
func GetExampleModelList(completion: ((ExampleModel?)/* or [ExampleModel]*/ -> Void)?) {
super.FireRequestWithURLSession(url: /* url here */, methodType: /* method type here */, headers: /* headers here */) { (responseModel) in
completion?(responseModel)
}
}
}
Usage
class MyLocationsController: UIViewController {
// MARK: Properties
// better to have in base class for the controller
var exampleModelService: ExampleModelService = ExampleModelService()
// MARK: Life Cycle Methods
override func viewDidLoad() {
super.viewDidLoad()
exampleModelService.GetExampleModelList(completion: { [weak self] (response) in
// model available here
})
}
}
Basically, you need to conform Codable protocol in your model classes, for this you need to implement 2 methods, one for code your model and another for decode your model from JSON
func encode(to encoder: Encoder) throws
required convenience init(from decoder: Decoder) throws
After that you will be able to use JSONDecoder class provided by apple to decode your JSON, and return an array (if were the case) or an object of your model class.
class ExampleModel: Codable {
var commentId : String?
var content : String?
//if your JSON keys are different than your property name
enum CodingKeys: String, CodingKey {
case commentId = "CommentId"
case content = "Content"
}
}
Then using JSONDecoder you can get your model array like this
do {
var arrayOfOrders : [ExampleModel] = try JSONDecoder().decode([ExampleModel].self, from: dataNew)
}
catch {
}
First of all, I can recommend you to use this application -quicktype- for turning json file to class or struct (codable) whatever you want. enter link description here.
After that you can create a generic function to get any kind of codable class and return that as a response.
func taskHandler<T:Codable>(type: T.Type, useCache: Bool, urlRequest: URLRequest, completion: #escaping (Result<T, Error>) -> Void) {
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let error = error {
print("error : \(error)")
}
if let data = data {
do {
let dataDecoded = try JSONDecoder().decode(T.self, from: data)
completion(.success(dataDecoded))
// if says use cache, let's store response data to cache
if useCache {
if let response = response as? HTTPURLResponse {
self.storeDataToCache(urlResponse: response, urlRequest: urlRequest, data: data)
}
}
} catch let error {
completion(.failure(error))
}
} else {
completion(.failure(SomeError))
}
}
task.resume()
}

Cannot convert value of type 'Dictionary<String, Any>?' to expected argument type 'Data'

I am still new to swift and i am trying to fetch json data and pass it to the next view as an object which i created. However, i am getting this error Cannot convert value of type 'Dictionary?' to expected argument type 'Data' when i try to user the decoder class. I am not sure what to do to fix it. I have tried changing Dictionary?' to Data in my completion handler but i am still getting errors.
This is my code :
Service call
class ServiceCall: NSObject, ServiceCallProtocol, URLSessionDelegate {
let urlServiceCall: String?
let country: String?
let phone: String?
var search: SearchResultObj?
init(urlServiceCall: String,country: String, phone: String){
self.urlServiceCall = urlServiceCall
self.country = country
self.phone = phone
}
func fetchJson(request: URLRequest, customerCountry: String, mobileNumber: String, completion: ((Bool, Dictionary<String, Any>?) -> Void)?){
let searchParamas = CustomerSearch.init(country: customerCountry, phoneNumber: mobileNumber)
var request = request
request.httpMethod = "POST"
request.httpBody = try? searchParamas.jsonData()
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, Any>
let status = json["status"] as? Bool
if status == true {
print(json)
}else{
print(" Terrible failure")
}
} catch {
print("Unable to make an api call")
}
})
task.resume()
}
}
SearchViewModel
func searchDataRequested(_ apiUrl: String,_ country: String,_ phone:String) {
let service = ServiceCall(urlServiceCall: apiUrl, country: country, phone: phone)
let url = URL(string: apiUrl)
let request = URLRequest(url: url!)
let country = country
let phone = phone
service.fetchJson(request: request, customerCountry: country, mobileNumber: phone)
{ (ok, json) in
print("CallBack response : \(String(describing: json))")
let decoder = JSONDecoder()
let result = decoder.decode(SearchResultObj.self, from: json)
print(result.name)
// self.jsonMappingToSearch(json as AnyObject)
}
}
New error:
You are going to deserialize the JSON twice which cannot work.
Instead of returning a Dictionary return Data, this mistake causes the error, but there are more issues.
func fetchJson(request: URLRequest, customerCountry: String, mobileNumber: String, completion: (Bool, Data?) -> Void) { ...
Then change the data task to
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
if let error = error {
print("Unable to make an api call", error)
completion(false, nil)
return
}
completion(true, data)
})
and the service call
service.fetchJson(request: request, customerCountry: country, mobileNumber: phone) { (ok, data) in
if ok {
print("CallBack response :", String(data: data!, encoding: .utf8))
do {
let result = try JSONDecoder().decode(SearchResultObj.self, from: data!)
print(result.name)
// self.jsonMappingToSearch(json as AnyObject)
} catch { print(error) }
}
}
And you have to adopt Decodable in ServiceCall
class ServiceCall: NSObject, ServiceCallProtocol, URLSessionDelegate, Decodable { ...
Further I highly recommended to separate the class model from the code to retrieve the data.
The data returned from session's task can either be serialized with JSONSerialization or decode it with JSONDecoder
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
either
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, Any>
OR
let result = try decoder.decode([item].self,data!)
the second argument of the decode method expects a parameter of type Data not Dictionary
you have to only edit the completion of fetchJson to return Bool,Data instead of Bool,Dictionary,and remove JSONSerialization code from it

Swift 4 send POST request as x-www-form-urlencoded

I want to send a POST request to my php 7 server which accepts data as application/x-www-form-urlencoded. The data I have is inside a Struct and I want to get every property of this struct as a parameter when I submit it.
This is the struct which handles my urlSession requests both GET and POST
XHR.swift
struct XHR {
enum Result<T> {
case success(T)
case failure(Error)
}
func urlSession<T>(method: String? = nil, file: String, data: Data? = nil, completionHandler: #escaping (Result<T>) -> Void) where T: Codable {
let file = file.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
// Set up the URL request
guard let url = URL.init(string: file) else {
print("Error: cannot create URL")
return
}
var urlRequest = URLRequest(url: url)
if method == "POST" {
urlRequest.httpMethod = "POST";
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.httpBody = data
print(urlRequest.httpBody)
}
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// vs let session = URLSession.shared
// make the request
let task = session.dataTask(with: urlRequest, completionHandler: {
(data, response, error) in
DispatchQueue.main.async { // Correct
guard let responseData = data else {
print("Error: did not receive data")
return
}
let decoder = JSONDecoder()
print(String(data: responseData, encoding: .utf8))
do {
let todo = try decoder.decode(T.self, from: responseData)
completionHandler(.success(todo))
} catch {
print("error trying to convert data to JSON")
//print(error)
completionHandler(.failure(error))
}
}
})
task.resume()
}
}
This is the functions which sends a POST request to the server:
VideoViewModel.swift
struct User: Codable {
let username: String
let password: String
static func archive(w:User) -> Data {
var fw = w
return Data(bytes: &fw, count: MemoryLayout<User>.stride)
}
static func unarchive(d:Data) -> User {
guard d.count == MemoryLayout<User>.stride else {
fatalError("BOOM!")
}
var w:User?
d.withUnsafeBytes({(bytes: UnsafePointer<User>)->Void in
w = UnsafePointer<User>(bytes).pointee
})
return w!
}
}
enum Login {
case success(User)
case failure(Error)
}
func login(username: String, password: String, completionHandler: #escaping (Login) -> Void) {
let thing = User(username: username, password: password)
let dataThing = User.archive(w: thing)
xhr.urlSession(method: "POST", file: "https://kida.al/login_register/", data: dataThing) { (result: XHR.Result<User>) in
switch result {
case .failure(let error):
completionHandler(.failure(error))
case .success(let user):
//let convertedThing = User.unarchive(d: user)
completionHandler(.success(user))
}
}
}
And I call it like this:
videoViewModel.login(username: "rexhin", password: "bonbon") { (result: VideoViewModel.Login) in
switch result {
case .failure(let error):
print("error")
case .success(let user):
print(user)
}
}
From PHP I can see that a POST request is submitted successfully but when I try to get the username field by doing $_POST["username"] I get Undefined index:
Full code of the app can be seen here https://gitlab.com/rexhin/ios-kida.git
I used below code in swift 4
guard let url = URL(string: "http://192.168.88.129:81/authenticate") else {
return
}
let user1 = username.text!
let pass = passwordfield.text!
print(user1)
print(pass)
let data : Data = "username=\(user1)&password=\(pass)&grant_type=password".data(using: .utf8)!
var request : URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
request.setValue(NSLocalizedString("lang", comment: ""), forHTTPHeaderField:"Accept-Language");
request.httpBody = data
print("one called")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// vs let session = URLSession.shared
// make the request
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error
{
print(error)
}
else if let response = response {
print("her in resposne")
}else if let data = data
{
print("here in data")
print(data)
}
DispatchQueue.main.async { // Correct
guard let responseData = data else {
print("Error: did not receive data")
return
}
let decoder = JSONDecoder()
print(String(data: responseData, encoding: .utf8))
do {
// let todo = try decoder.decode(T.self, from: responseData)
// NSAssertionHandler(.success(todo))
} catch {
print("error trying to convert data to JSON")
//print(error)
// NSAssertionHandler(.failure(error))
}
}
})
task.resume()
}
You are passing the result of User.archive(w: thing) as the data embedded in the request body, which may never work. Generally, your archive(w:) and unarchive(d:) would never generate any useful results and you should better remove them immediately.
If you want to pass parameters where x-www-form-urlencoded is needed, you need to create a URL-query-like string.
Try something like this:
func login(username: String, password: String, completionHandler: #escaping (Login) -> Void) {
let dataThing = "username=\(username)&password=\(password)".data(using: .utf8)
xhr.urlSession(method: "POST", file: "https://kida.al/login_register/", data: dataThing) { (result: XHR.Result<User>) in
//...
}
}
The example above is a little bit too simplified, that you may need to escape username and/or password before embedding it in a string, when they can contain some special characters. You can find many articles on the web about it.
Another way of doing this is as follows:
Add the URLEncodedFormEncoder.swift into your project. This is a custom URLEncodedFormEncoder from Alamofire / Vapor.
Conform your model to native Swift Encodable protocol, just as you do with JSON coding.
Encode the model just as you do during json encoding
// example
let requstModel = OpenIDCTokenRequest(
clientId: clientId,
clientSecret: clientSecret,
username: username,
password: password
)
guard let requestData: Data = try? URLEncodedFormEncoder().encode(requstModel) else {
return // handle encoding error
}
Quoting from this post
In PHP, a variable or array element which has never been set is
different from one whose value is null; attempting to access such an
unset value is a runtime error.
The Undefined index error occurs when you try to access an unset variable or an array element. You should use function isset inorder to safely access the username param from the POST body. Try the below code in your PHP file.
if (isset($_POST["username"]))
{
$user= $_POST["username"];
echo 'Your Username is ' . $user;
}
else
{
$user = null;
echo "No user name found";
}

'Callback' is a missing argument in call?

I have a Seperated Swift file for the call. this looks like this:
var DEVICEBUNDLE_API_ROOT = "https://apps-dev.profects.nl/profects-apps/current/web/app.php/api/v2/device"
var session = NSURLSession.sharedSession()
init(action: NSString, data: NSString, callback: (success: Bool, data: NSDictionary) -> Void) {
var body = "{\"action\":\"" + action + "\",\"data\":" + data + "}";
var request = NSMutableURLRequest(URL: NSURL(string: DEVICEBUNDLE_API_ROOT)!)
request.HTTPMethod = "POST"
request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding) // Use UTF-8
var task = session.dataTaskWithRequest(request, completionHandler: {
data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Response: \(strData)")
var json = NSJSONSerialization.JSONObjectWithData(data, options : .MutableLeaves, error: nil) as? NSDictionary
if let parsedJSON = json
{
if let status = parsedJSON["status"] as? NSDictionary
{
if let statusCode = status["code"] as? NSString
{
if let responseData = parsedJSON["data"] as? NSDictionary
{
callback(success: statusCode == "201", data: responseData)
}
else
{
callback(success: false, data: NSDictionary())
}
}
}
}
})
task.resume()
}
The call for the login looks like this:
var request = JSONRequest("registerDeviceId", "{\"email\":\"" + usernameField.text + "\",\"password\":\"" + passwordField.text + "\", \"UUID\":\"Tset124235346456457567\", \"OS\":\"Android\"}")
Now an error shows up saying 'Missing Argument for parameter 'callback' in call'
How can I fix this? I already tried adding an value "" at the end of the call.
You are missing the callback. This is the closure that will be called when the request has finished running.
let action = "registerDeviceId"
let data = ...whatever...
var request = JSONRequest(action: action, data: data, callback: { (success: Bool, data: NSDictionary) in
// Do something here with the success and data info that you got from the request
return
})
More information about closures

Send SMS with Twilio in Swift

I try to use Twilio as an service provider but they have no examples for Swift that I understand.
My task is to send SMS to a number using Twilio API with Swift.
I have a Twilio.com account - and that one is working. But how do I do this in Swift code in a easy manner.
Twilio does provide a library - but that is meant for C# not for Swift (and using a bridging header seems too complicated!)
Here is the C# example, I need a easy 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);
}
}
Twilio evangelist here.
To send a text message from Swift you can just make a request directly to Twilios REST API. That said, I would not recommend doing this from an iOS app (or any other client app) as it requires you to embed your Twilio account credentials in the app, which is dangerous. I would instead recommend sending the SMS from a server side application.
If you do want to send the message from your app, there are a couple of Swift libraries I know of that simplify making HTTP requests:
Alamofire - from Mattt Thompson, creator of AFNetworking - used in the example here: https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html
SwiftRequest - from Ricky Robinett of Twilio
To make the request using SwiftRequest, it would 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 that helps.
recently I have gone through Twilio docs and few SO post.
you can send SMS with following code snip 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 goes fine..You should receive message like this..
Here is the new Swift example for Passwordless authentication. For the 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");
}
})
If You are using server side Swift with Perfect.org
See this Blog
http://perfecttwilio.blogspot.in
The answer by "Devin Rader" is perfect. For any other users like me, the following is the full converted code for SwiftRequest for swift 3.0. The original code is by Ricky Robinett.
Please let us know if any errors.
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 to use above class as mentioned by "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))")
}
});
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()
}

Resources