can not get access token from api - ios

enter image description hereI'm new to Swift and I just faced a problem . any help and suggestion is welcome, also i've seen Alomofire, but I was not able to setup Alamofire because of some errors, and Also I need help in Alamofire :|
request.addValue("application/json", forHTTPHeaderField:
"Accept")
request.addValue("application/x-www-form-urlencoded",
forHTTPHeaderField: "Content-Type")
let postString = ["grant_type" : "password" ,
"username" : EntPhoneNumber.text! ,
"password" : EntPassword.text! ,] as [String :
Any]
do {
request.httpBody = try JSONSerialization.data(withJSONObject:
postString)
}catch let error {
print(error.localizedDescription)
DisplayMessage(UserMessage: "Something went wrong , please try
again!")
return
}
let task = URLSession.shared.dataTask(with: request)
{
(data : Data? , response : URLResponse? , error : Error?) in
self.removeActivtyIndicator(activityIndicator:
MyActivityIndicator)
if error != nil
{
self.DisplayMessage(UserMessage: "1Could not successfully
perform this request , please try again later.")
print("error = \(String(describing : error))")
return
}
// let's convert response sent from a server side code to a
NSDictionary object:
do { let json = try JSONSerialization.jsonObject(with: data!,
options: .mutableContainers) as? NSDictionary
print(json!)
if let parseJSON = json
{
let userID = parseJSON["grant_type"] as? String
print("access_token : \(String(describing: userID))");
if userID == nil
{
//display an alert dialog with a friendly error
message
self.DisplayMessage(UserMessage: "2Could not
successfully perform this request , please try later.")
return
}
else
{
self.DisplayMessage(UserMessage: "3successfully
loged in.")
}
}
...
as you can see this is my code which i'm posting a request to api to get an access_token but i receive an error :
{error = "invalid_request";
"error_description" = "The mandatory 'grant_type' parameter is missing.";
}
These are the parameters that I should post to API and in postman it works properly but my code does not work at all in compiler.

you are making it too complex
let postString = ["grant_type" : "password" ,
"username" : EntPhoneNumber.text! ,
"password" : EntPassword.text! ,] as [String :
Any]
Alamofire.request(URL, method: .post, parameters: postString, encoding: URLEncoding.methodDependent, headers: nil).responseJSON { response in
if let json = response.result.value {
print("Response: ",json)
}
}
try this.
This is all you need. If you have any doubt ask here.

Follow this link to install Alamofire using CocoaPods
https://www.raywenderlich.com/156971/cocoapods-tutorial-swift-getting-startedenter link description here
I have created this custom method for API request.
func request(_ method: HTTPMethod
, _ URLString: String
, parameters: [String : AnyObject]? = [:]
, headers: [String : String]? = [:]
, completion:#escaping (Any?) -> Void
, failure: #escaping (Error?) -> Void) {
Alamofire.request(URLString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
switch response.result {
case .success:
completion(response.result.value!)
case .failure(let error):
failure(error)
}
}
}

You need to encode the login and password parameters in query while sending the request. Lets create a separate Network class which has loginRequest(username:password) function which makes the API request to the server with username and password params. The login method has a closure which either returns a userId string or Error.
class Networking {
enum NetworkError: Error {
case parsingData
case jsonParsing
case emptyData
case apiError(error: Error)
}
func parseJSON(from data: Data) throws -> Any {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
return json
} catch {
return error
}
}
func loginRequest(username: String, password: String, completion: #escaping (String?, NetworkError?) -> ()) {
var request = URLRequest(url: URL(string: "api.nahadeh.com/connect/token")!)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let queryParams = "grant_type=password&username=\(username)&password=\(password)"
request.httpBody = queryParams.data(using: .utf8, allowLossyConversion: false)
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error != nil else {
completion(nil, NetworkError.apiError(error: error!))
return
}
guard let data = data else {
return completion(nil, NetworkError.emptyData)
}
do {
let json = try self.parseJSON(from: data) as! [String: Any]
guard let accessToken = json["access_token"] as? String else {
completion(nil, NetworkError.jsonParsing)
return
}
completion(accessToken, nil)
} catch {
completion(nil, NetworkError.jsonParsing)
}
}.resume()
}
}
Now from your UIViewController subclass you can create the instance of Networking class and call the login method with username and password params
class LoginViewController: UIViewController {
let networking = Networking()
func login(username: String, password: String) {
networking.loginRequest(username: username, password: password) { (token, error) in
if let token = token {
print(token)
self.displayMessage("Successfully loged in. Go to home screen")
return
}
if let nError = error {
switch nError {
case .jsonParsing:
self.displayMessage("jsonParsingError")
case .emptyData:
self.displayMessage("emptyData")
case .apiError(let error):
print(error.localizedDescription)
self.displayMessage("Could not successfully perform this request , please try later.")
case .parsingData:
self.displayMessage("parsingData")
}
}
}
}
func displayMessage(_ message: String, completion: (() -> Void)? = nil) {
let alert = UIAlertController(title: "Message", message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: completion)
}
}
Using Alamofire it's very easy to make API request, just pass the params and it will do the work for you
func loginRequest(username: String, password: String, completion: #escaping (String?, Error?) -> ()) {
let params: [String: String] = [
"grant_id": "password",
"username": username,
"password" : password
]
Alamofire.request("api.nahadeh.com/connect/token", method: .post, parameters: params, encoding: .httpBody, headers: nil).validate().response { (response) in
switch response.result {
case .success(let value):
let accessToken = value["access_token"]
completion(accessToken, nil)
case .failure(let error):
completion(nil, error)
}
}
}

Related

SwiftUI Login Issue

I am making an app where I am using API to create login interface.
In my LoginViewModel class I have following login function
import Foundation
class LoginViewModel: ObservableObject {
#Published var loginuser : Login?
// func login(username: String, password: String, callback : #escaping (Bool,LoginData,String) -> Void) {
func login(with params: [String: Any], completionHandler: #escaping (Bool,LoginData,String) -> Void) {
// let parameters: [String: Any] = [
// "email": username,
// "password": password
// ]
var semaphore = DispatchSemaphore (value: 0)
guard let url = URL(string: "https://xxxxxxxxx/v1//user/login")else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//request.addValue("token", forHTTPHeaderField: "Authorization")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: params)
} catch let error {
print(error.localizedDescription)
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
print(String(data: data, encoding: .utf8)!)
}//urlsession
task.resume()
}//login func
}
And in my view I have button whose action has following code
Button(action: {
let params = ["email": userName,
"password": password]
viewModel.login(with: params) { success, data, message in
if success==true {
UserDefaultsStore.isUserLoggedIn = true
// UserDefaultsStore.loginuser = login
showsAlert4 = true
print ("cat1")
}
else
{
print ("cat2")
}
}
}, label: {
Image("btn_arrow")
While I can confirm the API is being read fine as console puts out data from this line in func login
print(String(data: data, encoding: .utf8)!)
What I can not get to work is show "cat1" or "cat2" message in case of successful or unsuccessful login attempt. In fact this piece of code just never executes
if success==true {
UserDefaultsStore.isUserLoggedIn = true
// UserDefaultsStore.loginuser = login
showsAlert4 = true
print ("cat1")
}
else
{
print ("cat2")
}
Any idea where I am going wrong in this? Any help will be appreciated. Thanks
I have tried changing completionHandler: to callback: in func login but that changes nothing.
As someone in the comments mentioned, you are not calling your completionHandler at all. You could also drop the semaphore as it is not needed. Or maybe I am missing the point of the semaphore and you can elaborate on that.
import Foundation
class LoginViewModel: ObservableObject {
#Published var loginuser : Login?
func login(with params: [String: Any], completionHandler: #escaping (Bool,LoginData,String) -> Void) {
var semaphore = DispatchSemaphore (value: 0)
guard let url = URL(string: "https://xxxxxxxxx/v1//user/login")else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: params)
} catch let error {
print(error.localizedDescription)
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
completionHandler(false, nil, "Error") -> ON FAILURE
return
}
print(String(data: data, encoding: .utf8)!)
completionHandler(true, data, "") -> ON SUCCESS
}
task.resume()
}

iOS create generic Alamofire request using swift

Recently I have started learning iOS app development using swift so I am new to it. I want to implement rest api call in swift & found that we can achieve this using URLRequest. So I have written generic method to call all type(like get, put, post) of rest api as below.
import Foundation
//import Alamofire
public typealias JSON = [String: Any]
public typealias HTTPHeaders = [String: String];
public enum RequestMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
public enum Result<Value> {
case success(Value)
case failure(Error)
}
public class apiClient{
private var base_url:String = "https://api.testserver.com/"
private func apiRequest(endPoint: String,
method: RequestMethod,
body: JSON? = nil,
token: String? = nil,
completionHandler: #escaping (Data?, URLResponse?, Error?) -> Void) {
let url = URL(string: (base_url.self + endPoint))!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue
urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
if let token = token {
urlRequest.setValue("bearer " + token, forHTTPHeaderField: "Authorization")
}
if let body = body {
urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: body)
}
let session = URLSession(configuration: .default)
let task = session.dataTask(with: urlRequest) { data, response, error in
//NSLog(error)
completionHandler(data, response, error)
}
task.resume()
}
public func sendRequest<T: Decodable>(for: T.Type = T.self,
endPoint: String,
method: RequestMethod,
body: JSON? = nil,
token: String? = nil,
completion: #escaping (Result<T>) -> Void) {
return apiRequest(endPoint: endPoint, method: method, body:body, token: token) { data, response, error in
guard let data = data else {
return completion(.failure(error ?? NSError(domain: "SomeDomain", code: -1, userInfo: nil)))
}
do {
let decoder = JSONDecoder()
try completion(.success(decoder.decode(T.self, from: data)))
} catch let decodingError {
completion(.failure(decodingError))
}
}
}
}
this is how I call it method from controller
public func getProfile(userId :Int, objToken:String) -> Void {
let objApi = apiClient()
objApi.sendRequest(for: ProfileDetails.self,
endPoint:"api/user/profile/\(userId)",
method: .get,
token: objToken,
completion:
{(userResult: Result<ProfileDetails>) -> Void in
switch userResult
{
case .success(let value):
if value.respCode == "01" {
print(value.profile)
do {
//... ddo some taks like store response in local db or else
} catch let error as NSError {
// handle error
print(error)
}
}
else {
//do some task
}
break
case .failure(let error):
print(error)
break
}
})
}
I am decoding server response in below model
class ProfileDetails : Response, Decodable {
var appUpdate : AppUpdate?
var profile : Profile?
enum CodingKeys: String, CodingKey {
case profile = "profile"
case respCode = "resp_code"
case respMsg = "resp_msg"
}
public required convenience init(from decoder: Decoder) throws {
self.init()
let values = try decoder.container(keyedBy: CodingKeys.self)
self.profile = try values.decodeIfPresent(Profile.self, forKey: .profile)
self.respCode = try values.decodeIfPresent(String.self, forKey: .respCode)!
self.respMsg = try values.decodeIfPresent(String.self, forKey: .respMsg)
}
}
This code is not able to handle error response like 401, 404 etc from server. So what I am looking for, is to convert this api (URLRequest)request to generic Alamofire request with error handling like 401, 404 etc. I have install Alamofire pods. Is there anyone who has developed generic Alamofire request method with decoding & error handling?
Thanks in advance :)
Git link: https://github.com/sahilmanchanda2/wrapper-class-for-alamofire
Here is my version(Using Alamofire 5.0.2):
import Foundation
import Alamofire
class NetworkCall : NSObject{
enum services :String{
case posts = "posts"
}
var parameters = Parameters()
var headers = HTTPHeaders()
var method: HTTPMethod!
var url :String! = "https://jsonplaceholder.typicode.com/"
var encoding: ParameterEncoding! = JSONEncoding.default
init(data: [String:Any],headers: [String:String] = [:],url :String?,service :services? = nil, method: HTTPMethod = .post, isJSONRequest: Bool = true){
super.init()
data.forEach{parameters.updateValue($0.value, forKey: $0.key)}
headers.forEach({self.headers.add(name: $0.key, value: $0.value)})
if url == nil, service != nil{
self.url += service!.rawValue
}else{
self.url = url
}
if !isJSONRequest{
encoding = URLEncoding.default
}
self.method = method
print("Service: \(service?.rawValue ?? self.url ?? "") \n data: \(parameters)")
}
func executeQuery<T>(completion: #escaping (Result<T, Error>) -> Void) where T: Codable {
AF.request(url,method: method,parameters: parameters,encoding: encoding, headers: headers).responseData(completionHandler: {response in
switch response.result{
case .success(let res):
if let code = response.response?.statusCode{
switch code {
case 200...299:
do {
completion(.success(try JSONDecoder().decode(T.self, from: res)))
} catch let error {
print(String(data: res, encoding: .utf8) ?? "nothing received")
completion(.failure(error))
}
default:
let error = NSError(domain: response.debugDescription, code: code, userInfo: response.response?.allHeaderFields as? [String: Any])
completion(.failure(error))
}
}
case .failure(let error):
completion(.failure(error))
}
})
}
}
The above class uses latest Alamofire version (as of now Feb 2020), This class covers almost every HTTP Method with option to send data in Application/JSON format or normal. With this class you get a lot of flexibility and it automatically converts response to your Swift Object.
Look at the init method of this class it has:
data: [String,Any] = In this you will put your form data.
headers: [String:String] = In this you can send custom headers that you want to send along with the request
url = Here you can specify full url, you can leave it blank if you already have defined baseurl in Class. it comes handy when you want to consume a REST service provided by a third party. Note: if you are filling the url then you should the next parameter service should be nil
service: services = It's an enum defined in the NetworkClass itself. these serves as endPoints. Look in the init method, if the url is nil but the service is not nil then it will append at the end of base url to make a full URL, example will be provided.
method: HTTPMethod = here you can specify which HTTP Method the request should use.
isJSONRequest = set to true by default. if you want to send normal request set it to false.
In the init method you can also specify common data or headers that you want to send with every request e.g. your application version number, iOS Version etc
Now Look at the execute method: it's a generic function which will return swift object of your choice if the response is success. It will print the response in string in case it fails to convert response to your swift object. if the response code doesn't fall under range 200-299 then it will be a failure and give you full debug description for detailed information.
Usage:
say we have following struct:
struct Post: Codable{
let userId: Int
let id: Int
let title: String
let body: String
}
Note the base url defined in NetworkClass https://jsonplaceholder.typicode.com/
Example 1: Sending HTTP Post with content type Application/JSON
let body: [String : Any] = ["title": "foo",
"body": "bar",
"userId": 1]
NetworkCall(data: body, url: nil, service: .posts, method: .post).executeQuery(){
(result: Result<Post,Error>) in
switch result{
case .success(let post):
print(post)
case .failure(let error):
print(error)
}
}
output:
Service: posts
data: ["userId": 1, "body": "bar", "title": "foo"]
Post(userId: 1, id: 101, title: "foo", body: "bar")
HTTP 400 Request
NetworkCall(data: ["email":"peter#klaven"], url: "https://reqres.in/api/login", method: .post, isJSONRequest: false).executeQuery(){
(result: Result) in
switch result{
case .success(let post):
print(post)
case .failure(let error):
print(error)
}
}
output:
Service: https://reqres.in/api/login
data: ["email": "peter#klaven"]
Error Domain=[Request]: POST https://reqres.in/api/login
[Request Body]:
email=peter%40klaven
[Response]:
[Status Code]: 400
[Headers]:
Access-Control-Allow-Origin: *
Content-Length: 28
Content-Type: application/json; charset=utf-8
Date: Fri, 28 Feb 2020 05:41:26 GMT
Etag: W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q"
Server: cloudflare
Via: 1.1 vegur
cf-cache-status: DYNAMIC
cf-ray: 56c011c8ded2bb9a-LHR
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
x-powered-by: Express
[Response Body]:
{"error":"Missing password"}
[Data]: 28 bytes
[Network Duration]: 2.2678009271621704s
[Serialization Duration]: 9.298324584960938e-05s
[Result]: success(28 bytes) Code=400 "(null)" UserInfo={cf-ray=56c011c8ded2bb9a-LHR, Access-Control-Allow-Origin=*, Date=Fri, 28 Feb 2020 05:41:26 GMT, expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct", Server=cloudflare, Etag=W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q", x-powered-by=Express, Content-Type=application/json; charset=utf-8, Content-Length=28, Via=1.1 vegur, cf-cache-status=DYNAMIC}
with custom headers
NetworkCall(data: ["username":"sahil.manchanda2#gmail.com"], headers: ["custom-header-key" : "custom-header-value"], url: "https://httpbin.org/post", method: .post).executeQuery(){(result: Result) in
switch result{
case .success(let data):
print(data)
case .failure(let error):
print(error)
}
}
output:
Service: https://httpbin.org/post
data: ["username": "sahil.manchanda2#gmail.com"]
{
"args": {},
"data": "{\"username\":\"sahil.manchanda2#gmail.com\"}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "br;q=1.0, gzip;q=0.9, deflate;q=0.8",
"Accept-Language": "en;q=1.0",
"Content-Length": "41",
"Content-Type": "application/json",
"Custom-Header-Key": "custom-header-value",
"Host": "httpbin.org",
"User-Agent": "NetworkCall/1.0 (sahil.NetworkCall; build:1; iOS 13.2.2) Alamofire/5.0.2",
"X-Amzn-Trace-Id": "Root=1-5e58a94f-fab2f24472d063f4991e2cb8"
},
"json": {
"username": "sahil.manchanda2#gmail.com"
},
"origin": "182.77.56.154",
"url": "https://httpbin.org/post"
}
typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))
In the last example you can see typeMismatch at the end, I tried to pass [String:Any] in the executeQuery but since the Any doesn't confirm to encodable I had to use String.
I use EVReflection with alamofire and i think this is one of the best combination to work with.
Use URLRequestConvertible protocol of Alamofire.
This is what i follow.
Just for reference purpose.
Make enum for your all endpoint and confirm that enum to URLRequestConvertible.
enum Router: URLRequestConvertible {
//your all endpoint
static var authToken = ""
case login([String:Any])
var route: Route {
switch self {
case .Login(let dict):
return Route(endPoint: "api/addimagedata", httpMethod: .post)
}
}
func asURLRequest() throws -> URLRequest {
var requestUrl = EnvironmentVariables.baseURL
if let queryparams = route.queryParameters {
requestUrl.appendQueryParameters(queryparams)
}
var mutableURLRequest = URLRequest(url: requestUrl.appendingPathComponent(route.endPath))
mutableURLRequest.httpMethod = route.method.rawValue
//FIXME:- Change the Userdefault Key
if Router.authToken.isEmpty, let token = UserDefaults.standard.string(forKey: "Key"), !token.isEmpty {
Router.authToken = token
}
//FIXME:- Set Mutable Request Accordingly
mutableURLRequest.setValue("Bearer \(Router.authToken)", forHTTPHeaderField: "Authorization")
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")
if route.method == .get {
return try Alamofire.URLEncoding.default.encode(mutableURLRequest, with: route.parameters)
}
return try Alamofire.JSONEncoding.default.encode(mutableURLRequest, with: route.parameters)
}
}
Make One Structure as per your requirement.
struct Route {
let endPath: String
let method: Alamofire.HTTPMethod
var parameters: Parameters?
var queryParameters : [String:String]?
var encoding: Alamofire.ParameterEncoding {
switch method {
case .post, .put, .patch, .delete:
return JSONEncoding()
default:
return URLEncoding()
}
}
}
Now make one generic function that accept URLRequestConvertible and return your model in closure. Something like this.
func GenericApiCallForObject<T : URLRequestConvertible, M : EVObject>(router : T, showHud : Bool = true ,responseModel : #escaping (M) -> ()) {
view.endEditing(true)
if !isConnectedToInternet {
showNetworkError()
return
}
if showhud ? showHud() : ()
Alamofire.request(router).responseObject { (response: DataResponse<M>) in
self.HandleResponseWithErrorForObject(response: response) { (isSuccess) in
if isSuccess {
if let value = response.result.value {
responseModel(value)
}
}
})
}
}
Now make one generic function that accept your response and handle the error for you. Something like this.
func HandleResponseWithErrorForObject<M : EVObject>(response : DataResponse<M>, isSuccess : #escaping (Bool) -> ()) {
print(response)
hideHud()
switch response.response?.statusCode ?? 0 {
case 200...299:
isSuccess(true)
case 401:
isSuccess(false)
showSessionTimeOutError()
case -1005,-1001,-1003:
break
default:
isSuccess(false)
// Parse your response and show error in some way.
}
}
Now Finally, how to use it right??! Indeed now its very simple just two lines of code and you are good to go.
GenericApiCallForObject(router: Router.Login(["xyz":"xyz"])) { (response : GeneralModel) in
print(response)
}
Please note that this will only work if you are getting object in response. If there is an array or string you have to make separate function for that and procedure for that is same as above. You will only get response if there is a success otherwise HandleResponseWithErrorForObject function will automatically handle it for you. Also, some variables might be missing in above explanation.
I'm sharing a specific part for error handling on my REST api.
It will decode inside the following block and probably you can use it for reference.
As you can see that's very simple getting a code and translate into an enumeration.
Alamofire allow that but it depends on your version of library.
Sometimes depends your REST api how handle errors internally, they can not throw a code for example if its Java backend, they can encapsulate the exceptions.
public enum RESTError: Error {
case BadRequest(String, [String]?)
case InternalError(String)
case UnAuthorized(String, [String]?)
case NotFound(String)
case Success
/// <#Description#>
///
/// - Parameters:
/// - code: <#code description#>
/// - message: <#message description#>
/// - globalErrors: <#globalErrors description#>
/// - Returns: <#return value description#>
public static func fromCode(code: Int, message: String, globalErrors: [String]? = nil) -> RESTError {
switch code {
case 400: return RESTError.BadRequest(message, globalErrors)
case 401: return RESTError.UnAuthorized(message, globalErrors)
case 500: return RESTError.InternalError(message)
case 404: return RESTError.NotFound(message)
default: break
}
return RESTError.Success
}
}
Alamofire.request(urlRequest)
.validate(statusCode: 200...500)
.responseJSON(completionHandler: { (response: (DataResponse<Any>)) in
if let statusCode = response.response?.statusCode {
if statusCode != 200 {
// call handler errors function with specific message
if let arrayDictionary = response.result.value as? Dictionary<String,AnyObject> {
var error: RESTError?
if let code = arrayDictionary["status"] as? Int {
let message = arrayDictionary["message"] as! String
let globalErrors = arrayDictionary["globalErrors"] as? [String]
error = RESTError.fromCode(code: code, message: message, globalErrors: globalErrors)
} else {
// Build from error message without code.
let message = arrayDictionary["error_description"] as! String
let codeMsg = arrayDictionary["error"] as! String
let globalErrors = arrayDictionary["globalErrors"] as? [String]
if codeMsg == "invalid_token" && message.starts(with: "Access token expired") {
return
} else {
error = RESTError.fromCode(code: codeMsg, message: message, globalErrors: globalErrors)
}
}
if let _ = error {
errorHandler(error!)
} else {
errorHandler(RESTError.InternalError("Internal API rest error."))
}
} else {
errorHandler(RESTError.fromCode(code: statusCode, message: ""))
}
} else {
if let arrayDictionary = response.result.value as? Dictionary<String,AnyObject> {
handler(arrayDictionary)
}
}
} else {
if let error = response.error {
errorHandler(RESTError.InternalError(error.localizedDescription))
}
}
})
You probably need this function that uses the alamofilre Session Manager to perform requests. You can also set the cookies ant headers etc.. to this session manager so that you will have them to the rest of your requests.
import Alamofire
class NetworkManager : NSObject {
internal typealias SuccessCompletion = (Int?, Any?) -> Void?
internal typealias FailCompletion = (Int?, Error, Any?) -> Void?
var sessionManager : SessionManager!
var request : Request?
var headers : HTTPHeaders! = [:]
override init() {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
sessionManager = SessionManager(configuration: configuration)
}
func sendRequest(url: String?, method: String, parameters: [String: Any], success: SuccessCompletion?, fail: FailCompletion?){
var encoding : ParameterEncoding!
if HTTPMethod(rawValue: method) == HTTPMethod.post {
encoding = JSONEncoding.default
} else {
encoding = URLEncoding.default
}
request = sessionManager.request(url ?? "", method: HTTPMethod(rawValue: method)!, parameters: parameters, encoding: encoding, headers: headers)
.validate()
.responseData{response in
switch (response.result) {
case .success:
let statusCode = response.response?.statusCode
success?(statusCode, response.result.value)
self.request = nil
break
case .failure(let error):
let statusCode = response.response?.statusCode
fail?(statusCode, error, response.data)
self.request = nil
break
}
}
}
}
EDIT
To add Headers you can just add a function like this..
func updateJSONHeader(token: String) {
self.clearHeaders()
headers["AuthorizationToken"] = "\(token)"
}
For cookie
func setCookie(_ cookie : HTTPCookie?){
if let cookie = cookie {
HTTPCookieStorage.shared.setCookie(cookie)
}
}
Clear headers
func clearHeaders(){
headers = [:]
}
And keep in mind that it's a singleton class so whenever you change anything unless your server make some changes you still have your configuration, ex. the headers
The best way is create a custom validate method using DataRequest extension:
func customValidate() -> Self {
return self.validate { _, response, data -> Request.ValidationResult in
guard (400...599) ~= response.statusCode else { return .success(()) }
guard let data = data else { return .failure(MyAppGeneralError.generalResponseError) }
guard let errorResponse = try? JSONDecoder().decode(MyAppResponseError.self, from: data) else {
return .failure(MyAppGeneralError.generalResponseError)
}
if response.statusCode == 401 {
return .failure(MyAppGeneralError.unauthorizedAccessError(errorResponse))
}
return .failure(MyAppGeneralError.responseError(errorResponse))
}
}
With a client with a generic function where the generic is decodable using our custom validate.
class APIClient {
var session: Session
init(session: Session = Session.default) {
self.session = session
}
#discardableResult
func performRequest<T: Decodable>(request: URLRequestConvertible,
decoder: JSONDecoder = JSONDecoder(),
completion: #escaping (Result<T, AFError>) -> Void) -> DataRequest {
return AF.request(request).customValidate().responseDecodable(decoder: decoder, completionHandler: { (response: DataResponse<T, AFError>) in
completion(response.result)
})
}
func getProfile(userID: Int, _ completion: #escaping (Result<UserToken, AFError>) -> Void) {
performRequest(request: APIRouter.profile(userID: userID), completion: completion)
}
}
using a router a:
enum APIRouter: URLRequestConvertible {
case profile(userId :Int)
static let baseURLString = "https://myserver.com"
var method: HTTPMethod {
switch self {
case .profile:
return .get
}
}
var path: String {
switch self {
case .profile(let userID):
return "profile/\(userID)"
}
}
var body: Parameters {
return [:]
}
// MARK: URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try APIRouter.baseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
// Common Headers
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
// Encode body
urlRequest = try JSONEncoding.default.encode(urlRequest, with: body)
return urlRequest
}
}
import Foundation
import UIKit
import Alamofire
import SwiftyJSON
class AFWrapper: NSObject {
static let sharedInstance = AFWrapper()
//TODO :-
/* Handle Time out request alamofire */
func requestGETURL(_ strURL: String, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void)
{
Alamofire.request(strURL).responseJSON { (responseObject) -> Void in
//print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
//let title = resJson["title"].string
//print(title!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
//print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
}
This is something I have been working on! Not finished yet but could solve your issue. you can upgrade it to whatever you want.
typealias
typealias Closure<T> = (T)->()
typealias JSON = [String: Any]
Extension
extension JSONDecoder{
func decode<T : Decodable>(_ model : T.Type,
result : #escaping Closure<T>) ->Closure<Data>{
return { data in
if let value = try? self.decode(model.self, from: data){
result(value)
}
}
}
Protocol
//MARK:- protocol APIResponseProtocol
protocol APIResponseProtocol{
func responseDecode<T: Decodable>(to modal : T.Type,
_ result : #escaping Closure<T>) -> APIResponseProtocol
func responseJSON(_ result : #escaping Closure<JSON>) -> APIResponseProtocol
func responseFailure(_ error :#escaping Closure<String>)
}
Request:
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 300 // seconds
configuration.timeoutIntervalForResource = 500
alamofireManager = Alamofire.SessionManager(configuration: configuration)
func getRequest(forAPI api: String, params: JSON) -> APIResponseProtocol {
let responseHandler = APIResponseHandler()
var parameters = params
parameters["token"] = preference.string(forKey: USER_ACCESS_TOKEN)
alamofireManager.request(api,
method: .get,
parameters: parameters,
encoding: URLEncoding.default,
headers: nil)
.responseJSON { (response) in
print("Å api : ",response.request?.url ?? ("\(api)\(params)"))
switch response.result{
case .success(let value):
let json = value as! JSON
let error = json.string("error")
guard error.isEmpty else{
responseHandler.handleSuccess(value: value,data: response.data ?? Data())
case .failure(let error):
responseHandler.handleFailure(value: error.localizedDescription)
}
}
return responseHandler
}
Response Hanlder:
class APIResponseHandler : APIResponseProtocol{
init(){
}
var jsonSeq : Closure<JSON>?
var dataSeq : Closure<Data>?
var errorSeq : Closure<String>?
func responseDecode<T>(to modal: T.Type, _ result: #escaping Closure<T>) -> APIResponseProtocol where T : Decodable {
let decoder = JSONDecoder()
self.dataSeq = decoder.decode(modal, result: result)
return self
}
func responseJSON(_ result: #escaping Closure<JSON>) -> APIResponseProtocol {
self.jsonSeq = result
return self
}
func responseFailure(_ error: #escaping Closure<String>) {
self.errorSeq = error
}
func handleSuccess(value : Any,data : Data){
if let jsonEscaping = self.jsonSeq{
jsonEscaping(value as! JSON)
}
if let dataEscaping = dataSeq{
dataEscaping(data)
}
}
func handleFailure(value : String){
self.errorSeq?(value)
}
}
USAGE:
self?.apiInteractor?
.getRequest(forAPI: "https://maps.googleapis.com/maps/api/directions/json",
params: [
"origin" : "\(pickUpLatitude),\(pickUpLongitude)",
"destination" :"\(dropLatitude),\(dropLongitude)",
"mode" : "driving",
"units" : "metric",
"sensor" : "true",
"key" : "\(UserDefaults.value(for: .google_api_key) ?? "")"
])
.responseDecode(to: GoogleGeocode.self, { [weak self] (googleGecode) in
guard let welf = self,
let route = googleGecode.routes.first,
let leg = route.legs.first else{return}
welf.tripDetailModel?.arrivalFromGoogle = leg.duration.text ?? ""
welf.drawRoute(forRoute: route)
welf.calculateETA()
})
.responseJSON({ (json) in
debugPrint(json.description)
})
.responseFailure({ (error) in
debug(print: error)
})
just part of code, but try
let req = Alamofire.request(url, method: .get, parameters: nil)
then you can handle response code by using
req.response?.statusCode
and handle response by for example
req.responseString(completionHandler: <#T##(DataResponse<String>) -> Void#>)
or
req.responseJSON(completionHandler: <#T##(DataResponse<Any>) -> Void#>)
you have good example here

How to write alamofire request function that returns the response?

I am writing a function to call a POST request using AlamoFire. I am passing URL and parameters. I need to return the response of the Alamofire request.
This is my code:
func callAPI(params: Dictionary<String, Any>, url: String) -> Void {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.contentColor = UIColor.red
DispatchQueue.global().async {
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding(options: []), headers: nil).responseJSON { response in
DispatchQueue.main.async {
hud.hide(animated: true)
switch response.result{
case .success:
if let resultJson = response.result.value as? Dictionary<String,Any>{
print(resultJson)
// Success
}
case .failure(let error):
print(error)
//Failed
}
}
}
}
}
I want to return the response dictionary resultJson from this function. And I want to reuse this function for all API calls.
How can I rewrite this function to get the solution?
You can pass a closure as a parameter to the function like this
func callAPI(params: Dictionary<String, Any>, url: String, completion:#escaping (((Dictionary<String,Any>?) -> Void))) -> Void {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.contentColor = UIColor.red
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding(options: []), headers: nil).responseJSON { response in
hud.hide(animated: true)
switch response.result{
case .success:
if let resultJson = response.result.value as? Dictionary<String,Any>{
print(resultJson)
completion(resultJson)
// Success
}
case .failure(let error):
print(error)
completion(nil)
//Failed
}
}
}
Call the function with the closure
callAPI(params: [:], url: "") { resultJson in
guard let resultJson = resultJson else {
return
}
print(resultJson)
}
You should pass the clouser parameter.
After that when success execute completion(resultJson, nil) if server result error you should execute completion(nil, error.localizedDescription)
func callAPI(params: Dictionary<String, Any>, url: String , completion: #escaping (Dictionary<String,Any>?, String?) -> ()) -> Void { }

Web service is called twice

I have a problem with a webService call.
The problem is that when I call the service, and debug code, and print log in console, I'm sure my webService is only called once (log print once in console), but my request is apparently sent twice to the server and I have duplicate data in the list.
I know that it's not a server-side problem because it only happens on IOS (not Android).
Here is my code for call services:
public class PersistencyManager {
public func SendPostHttpRequest(baseURL: String, parameter: [String:Any], content: String, closure:#escaping ((_ success:JSON,_ error:NSError?) -> Void)) {
let manager = Alamofire.SessionManager.default
debugPrint("Request parameter ------>",parameter)
debugPrint(" Service URL -------> \(baseURL)")
if let url = URL(string: baseURL) {
var urlRequest = URLRequest(url: url)
urlRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
urlRequest.setURLEncodedFormData(parameters: parameter)
manager.request(urlRequest).responseJSON { response in
switch response.result {
case .success(let JSON) :
debugPrint("get Json response ---> \((JSON)) ")
closure(JSON,nil)
case .failure(let error):
closure(nil,error as NSError)
debugPrint("get error ---> \((error.localizedDescription)) ")
}
}
}
}
}
class LibraryAPI {
static let shareInstance : LibraryAPI = { LibraryAPI() }()
private let persistencyManager : PersistencyManager
init() {
persistencyManager = PersistencyManager()
}
func GetPostResponse(baseURL : String,parameters:[String:Any],contentType: String,closure:#escaping ((_ success:PersistencyManager.JSON,_ error:NSError?) -> Void)) {
persistencyManager.SendPostHttpRequest(baseURL: baseURL, parameter: parameters, content: contentType, closure: { success, error in
closure(success, error)
})
}
}
class TransactionAPI: TransactionProtocol {
static let shareInstance: TransactionAPI = {TransactionAPI()}()
func AddNewManagerRequest(_ parameter: [String : Any], closure: #escaping (([String : Any]?, NSError?) -> Void)) {
let url = Constants.BaseURL + Constants.K_NEWREQPORTERAGE
LibraryAPI.shareInstance.GetPostResponse(baseURL: url, parameters: parameter, contentType: "JSON", closure: {success,error in
var response: [String:Any]?
if let json = success as? [String: Any] {
response = json
}
closure(response, error)
})
}
}
class AddNewOrderViewController: MainViewController {
private func RegisterForNewPorterageRequest() {
let time = Utilities.shareInstance.GetSystemTime()
guard let userID = UserDefaults.standard.value(forKey: "user_id") as? String else {
return
}
StartActivity(activityColor: Constants.ACTIVITY_COLOR)
let token = TokenCreator.shareInstance.CreateTokenWithUserID(userID: userID, methodName: Constants.M_NEWREQUESTPORTERAGE)
request.tok = token
request.time = time
request.user_id = userID
let jsonModel = Utilities.shareInstance.GetJsonForm(objectClass: request)
TransactionAPI.shareInstance.AddNewManagerRequest(jsonModel, closure: {[weak self] success,error in
guard let strongSelf = self else{
return
}
if error != nil {
OperationQueue.main.addOperation {
strongSelf.StopActivity()
strongSelf.CreateCustomTopField(text: Constants.serverError, color: Constants.ERROR_COLOR)
}
}
else {
if let response = success {
debugPrint("add request service call once")
if let status = response["status"] as? String {
if status == "succ" {
OperationQueue.main.addOperation {
strongSelf.presentResultAlert()
}
}else {
OperationQueue.main.addOperation {
strongSelf.StopActivity()
strongSelf.CreateCustomTopField(text: Constants.send_data_error, color: Constants.ERROR_COLOR)
}
}
}
}
}
})
}
}
After adding log to server, I made sure my request was sent twice to server.
All console log print once in console.
I don't know when I call service twice, and why my request was sent twice to the server.
I don't understand how the log be displayed once, but the service has been called twice?
Any help appreciated.
It's really confusing, but it works perfectly with this method.
i have this method in persistencyMangerClass and i using this method instead SendPostHttpRequest.What really is the difference between these two methods. :|
public func SendMultiPartRequestWith(baseUrl: String, parameters: [String : Any],closure: #escaping ((_ success:JSON,_ error:NSError? ) -> Void)){
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 30
manager.session.configuration.timeoutIntervalForResource = 15
debugPrint(" Service URL -------> \(baseUrl)")
debugPrint("Request parameter ------>",parameters)
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
manager.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
if let data = value as? Data {
let fileName = (key as String) + ".jpg"
let mimType = (key as String) + "/jpg"
multipartFormData.append(data, withName: key as String, fileName: fileName, mimeType: mimType)
}
else {
if let v = value as? String {
multipartFormData.append("\(v)".data(using: String.Encoding.utf8)!, withName: key as String)
}else {
multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: key as String)
}
}
}
}, usingThreshold: UInt64.init(), to: baseUrl, method: .post, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseString { response in
if let err = response.error{
closure(nil, err as NSError)
return
}
if let JSON = response.result.value {
closure(JSON, nil)
}
}
case .failure(let error):
closure(nil, error as NSError)
}
}
}

How to parse JSON response from Alamofire API in Swift?

Following code I have written and I am getting response in JSON also but the type of JSON is "AnyObject" and I am not able to convert that into Array so that I can use that.
Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
(request, response, JSON, error) in
println(JSON?)
}
The answer for Swift 2.0 Alamofire 3.0 should actually look more like this:
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON).responseJSON
{ response in switch response.result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
let response = JSON as! NSDictionary
//example if there is an id
let userId = response.objectForKey("id")!
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md
UPDATE for Alamofire 4.0 and Swift 3.0 :
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
//to get status code
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON)
}
}
like above mention you can use SwiftyJSON library and get your values like i have done below
Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
(request, response, data, error) in
var json = JSON(data: data!)
println(json)
println(json["productList"][1])
}
my json product list return from script
{ "productList" :[
{"productName" : "PIZZA","id" : "1","productRate" : "120.00","productDescription" : "PIZZA AT 120Rs","productImage" : "uploads\/pizza.jpeg"},
{"productName" : "BURGER","id" : "2","productRate" : "100.00","productDescription" : "BURGER AT Rs 100","productImage" : "uploads/Burgers.jpg"}
]
}
output :
{
"productName" : "BURGER",
"id" : "2",
"productRate" : "100.00",
"productDescription" : "BURGER AT Rs 100",
"productImage" : "uploads/Burgers.jpg"
}
Swift 3, Alamofire 4.4, and SwiftyJSON:
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.data != nil {
let json = JSON(data: response.data!)
let name = json["people"][0]["name"].string
if name != nil {
print(name!)
}
}
}
That will parse this JSON input:
{
people: [
{ name: 'John' },
{ name: 'Dave' }
]
}
I found the answer on GitHub for Swift2
https://github.com/Alamofire/Alamofire/issues/641
Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseJSON { request, response, result in
switch result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
case .Failure(let data, let error):
print("Request failed with error: \(error)")
if let data = data {
print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
}
}
}
I'm neither a JSON expert nor a Swift expert, but the following is working for me. :) I have extracted the code from my current app, and only changed "MyLog to println", and indented with spaces to get it to show as a code block (hopefully I didn't break it).
func getServerCourseVersion(){
Alamofire.request(.GET,"\(PUBLIC_URL)/vtcver.php")
.responseJSON { (_,_, JSON, _) in
if let jsonResult = JSON as? Array<Dictionary<String,String>> {
let courseName = jsonResult[0]["courseName"]
let courseVersion = jsonResult[0]["courseVersion"]
let courseZipFile = jsonResult[0]["courseZipFile"]
println("JSON: courseName: \(courseName)")
println("JSON: courseVersion: \(courseVersion)")
println("JSON: courseZipFile: \(courseZipFile)")
}
}
}
Hope this helps.
Edit:
For reference, here is what my PHP Script returns:
[{"courseName": "Training Title","courseVersion": "1.01","courseZipFile": "101/files.zip"}]
Swift 5
class User: Decodable {
var name: String
var email: String
var token: String
enum CodingKeys: String, CodingKey {
case name
case email
case token
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.email = try container.decode(String.self, forKey: .email)
self.token = try container.decode(String.self, forKey: .token)
}
}
Alamofire API
Alamofire.request("url.endpoint/path", method: .get, parameters: params, encoding: URLEncoding.queryString, headers: nil)
.validate()
.responseJSON { response in
switch (response.result) {
case .success( _):
do {
let users = try JSONDecoder().decode([User].self, from: response.data!)
print(users)
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
case .failure(let error):
print("Request error: \(error.localizedDescription)")
}
swift 3
pod 'Alamofire', '~> 4.4'
pod 'SwiftyJSON'
File json format:
{
"codeAd": {
"dateExpire": "2017/12/11",
"codeRemoveAd":"1231243134"
}
}
import Alamofire
import SwiftyJSON
private func downloadJson() {
Alamofire.request("https://yourlinkdownloadjson/abc").responseJSON { response in
debugPrint(response)
if let json = response.data {
let data = JSON(data: json)
print("data\(data["codeAd"]["dateExpire"])")
print("data\(data["codeAd"]["codeRemoveAd"])")
}
}
}
This was build with Xcode 10.1 and Swift 4
Perfect combination "Alamofire"(4.8.1) and "SwiftyJSON"(4.2.0). First you should install both pods
pod 'Alamofire' and pod 'SwiftyJSON'
The server response in JSON format:
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip;q=1.0, compress;q=0.5",
"Accept-Language": "en;q=1.0",
"Host": "httpbin.org",
"User-Agent": "AlamoFire TEST/1.0 (com.ighost.AlamoFire-TEST; build:1; iOS 12.1.0) Alamofire/4.8.1"
},
"origin": "200.55.140.181, 200.55.140.181",
"url": "https://httpbin.org/get"
}
In this case I want print the "Host" info : "Host": "httpbin.org"
Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in
switch response.result {
case .success:
print("Validation Successful)")
if let json = response.data {
do{
let data = try JSON(data: json)
let str = data["headers"]["Host"]
print("DATA PARSED: \(str)")
}
catch{
print("JSON Error")
}
}
case .failure(let error):
print(error)
}
}
Keep Calm and happy Code😎
I found a way to convert the response.result.value (inside an Alamofire responseJSON closure) into JSON format that I use in my app.
I'm using Alamofire 3 and Swift 2.2.
Here's the code I used:
Alamofire.request(.POST, requestString,
parameters: parameters,
encoding: .JSON,
headers: headers).validate(statusCode: 200..<303)
.validate(contentType: ["application/json"])
.responseJSON { (response) in
NSLog("response = \(response)")
switch response.result {
case .Success:
guard let resultValue = response.result.value else {
NSLog("Result value in response is nil")
completionHandler(response: nil)
return
}
let responseJSON = JSON(resultValue)
// I do any processing this function needs to do with the JSON here
// Here I call a completionHandler I wrote for the success case
break
case .Failure(let error):
NSLog("Error result: \(error)")
// Here I call a completionHandler I wrote for the failure case
return
}
I usually use Gloss library to serialize or deserialize JSON in iOS. For example, I have JSON that looks like this:
{"ABDC":[{"AB":"qwerty","CD":"uiop"}],[{"AB":"12334","CD":"asdf"}]}
First, I model the JSON array in Gloss struct:
Struct Struct_Name: Decodable {
let IJ: String?
let KL: String?
init?(json: JSON){
self.IJ = "AB" <~~ json
self.KL = "CD" <~~ json
}
}
And then in Alamofire responseJSON, I do this following thing:
Alamofire.request(url, method: .get, paramters: parametersURL).validate(contentType: ["application/json"]).responseJSON{ response in
switch response.result{
case .success (let data):
guard let value = data as? JSON,
let eventsArrayJSON = value["ABDC"] as? [JSON]
else { fatalError() }
let struct_name = [Struct_Name].from(jsonArray: eventsArrayJSON)//the JSON deserialization is done here, after this line you can do anything with your JSON
for i in 0 ..< Int((struct_name?.count)!) {
print((struct_name?[i].IJ!)!)
print((struct_name?[i].KL!)!)
}
break
case .failure(let error):
print("Error: \(error)")
break
}
}
The output from the code above:
qwerty
uiop
1234
asdf
in swift 5 we do like, Use typealias for the completion. Typlealias nothing just use to clean the code.
typealias response = (Bool,Any?)->()
static func postCall(_ url : String, param : [String : Any],completion : #escaping response){
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in
switch response.result {
case .success(let JSON):
print("\n\n Success value and JSON: \(JSON)")
case .failure(let error):
print("\n\n Request failed with error: \(error)")
}
}
}
The easy answer is to let AlamoFire do the decoding directly.
Surprisingly, you don't use the .responseJSON because that returns an untyped json object
Instead, you make your objects Decodable - and ask AF to decode directly to them
My json response contains an array of Account objects. I only care about the id and name keys (though there are many more)
struct Account:Codable {
let id:Int
let name:String
}
then simply
AF.request(url,
method: .get)
.responseDecodable(of:[Account].self) { response in
switch response.result {
case .success:
switch response.response?.statusCode {
case 200:
//response.value is of type [Account]
default:
//handle other cases
}
case let .failure(error):
//probably the decoding failed because your json doesn't match the expected format
}
}
let semaphore = DispatchSemaphore (value: 0)
var request = URLRequest(url: URL(string: Constant.localBaseurl2 + "compID")!,timeoutInterval: Double.infinity)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let response = response {
let nsHTTPResponse = response as! HTTPURLResponse
print(nsHTTPResponse)
}
if let error = error {
print ("\(error)")
return
}
if let data = data {
DispatchQueue.main.async {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase//or any other Decoder\
do{
let jsonDecoder = JSONDecoder()
let memberRecord = try jsonDecoder.decode(COMPLAINTSVC.GetComplaints.self, from: data)
print(memberRecord.message)
for detailData in memberRecord.message{
print(detailData)
}
}catch{
print(error.localizedDescription)
}
}
}
semaphore.signal()
}
task.resume()
semaphore.wait()
}
pod 'Alamofire'
pod 'SwiftyJSON'
pod 'ReachabilitySwift'
import UIKit
import Alamofire
import SwiftyJSON
import SystemConfiguration
class WebServiceHelper: NSObject {
typealias SuccessHandler = (JSON) -> Void
typealias FailureHandler = (Error) -> Void
// MARK: - Internet Connectivity
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
// MARK: - Helper Methods
class func getWebServiceCall(_ strURL : String, isShowLoader : Bool, success : #escaping SuccessHandler, failure : #escaping FailureHandler)
{
if isConnectedToNetwork() {
print(strURL)
if isShowLoader == true {
AppDelegate.getDelegate().showLoader()
}
Alamofire.request(strURL).responseJSON { (resObj) -> Void in
print(resObj)
if resObj.result.isSuccess {
let resJson = JSON(resObj.result.value!)
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
debugPrint(resJson)
success(resJson)
}
if resObj.result.isFailure {
let error : Error = resObj.result.error!
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
debugPrint(error)
failure(error)
}
}
}else {
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
class func getWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : #escaping SuccessHandler, failure :#escaping FailureHandler){
if isConnectedToNetwork() {
if isShowLoader == true {
AppDelegate.getDelegate().showLoader()
}
Alamofire.request(strURL, method: .get, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in
print(resObj)
if resObj.result.isSuccess {
let resJson = JSON(resObj.result.value!)
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
success(resJson)
}
if resObj.result.isFailure {
let error : Error = resObj.result.error!
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
failure(error)
}
})
}
else {
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
class func postWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : #escaping SuccessHandler, failure :#escaping FailureHandler)
{
if isConnectedToNetwork()
{
if isShowLoader == true
{
AppDelegate.getDelegate().showLoader()
}
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in
print(resObj)
if resObj.result.isSuccess
{
let resJson = JSON(resObj.result.value!)
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
success(resJson)
}
if resObj.result.isFailure
{
let error : Error = resObj.result.error!
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
failure(error)
}
})
}else {
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
class func postWebServiceCallWithImage(_ strURL : String, image : UIImage!, strImageParam : String, params : [String : AnyObject]?, isShowLoader : Bool, success : #escaping SuccessHandler, failure : #escaping FailureHandler)
{
if isConnectedToNetwork() {
if isShowLoader == true
{
AppDelegate.getDelegate().showLoader()
}
Alamofire.upload(
multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
multipartFormData.append(imageData, withName: "Image.jpg")
}
for (key, value) in params! {
let data = value as! String
multipartFormData.append(data.data(using: String.Encoding.utf8)!, withName: key)
print(multipartFormData)
}
},
to: strURL,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
//let datastring = String(data: response, encoding: String.Encoding.utf8)
// print(datastring)
}
case .failure(let encodingError):
print(encodingError)
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
let error : NSError = encodingError as NSError
failure(error)
}
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { (response) -> Void in
if response.result.isSuccess
{
let resJson = JSON(response.result.value!)
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
success(resJson)
}
if response.result.isFailure
{
let error : Error = response.result.error! as Error
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
failure(error)
}
}
case .failure(let encodingError):
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
let error : NSError = encodingError as NSError
failure(error)
}
}
)
}
else
{
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
}
==================================
Call Method
let aParams : [String : String] = [
"ReqCode" : Constants.kRequestCodeLogin,
]
WebServiceHelper.postWebServiceCall(Constants.BaseURL, params: aParams as [String : AnyObject]?, isShowLoader: true, success: { (responceObj) in
if "\(responceObj["RespCode"])" != "1"
{
let alert = UIAlertController(title: Constants.kAppName, message: "\(responceObj["RespMsg"])", preferredStyle: UIAlertControllerStyle.alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
}
alert.addAction(OKAction)
self.present(alert, animated: true, completion: nil)
}
else
{
let aParams : [String : String] = [
"Password" : self.dictAddLogin[AddLoginConstants.kPassword]!,
]
CommonMethods.saveCustomObject(aParams as AnyObject?, key: Constants.kLoginData)
}
}, failure:
{ (error) in
CommonMethods.showAlertWithError(Constants.kALERT_TITLE_Error, strMessage: error.localizedDescription,withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
})
}

Resources