I tried this particular API in postman, and it returns a fine result:
Thus, I created a parameter:
["JsonRequest": "{\"header\":\"GetLocationListReq\",\"accessKey\":\"fakeKey\"}"]
but when I pass this parameter when calling this API using swift and Alamofire in my Xcode project, I always get back an error.
For those who are interested, my apiRouter is:
//
// WINAPIRouter.swift
// Winner21
//
// Created by Lin Hairui on 27/4/17.
// Copyright © 2017 Pioneers & Leaders (Publishers). All rights reserved.
//
import Foundation
import Alamofire
enum WINAPIRouter : URLRequestConvertible {
static let baseURL = Constant.baseURL
case get(String)
case create([String:Any],String?)
case delete(String)
func asURLRequest() throws -> URLRequest {
var method : HTTPMethod {
switch self {
case .get:
return HTTPMethod.get
case .create:
return HTTPMethod.post
case .delete:
return HTTPMethod.delete
}
}
let params:(Dictionary<String, Any>?) = {
switch self {
case .get, .delete:
return nil
case .create(let params, _):
var fieldParams = params
fieldParams["accessKey"] = Constant.kAPIAccessKey
let jsonData: NSData
do {
jsonData = try JSONSerialization.data(withJSONObject: fieldParams, options: JSONSerialization.WritingOptions()) as NSData
let jsonString = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue) as! String
let authParam : [String : Any] = [
"JsonRequest" : jsonString
]
print("google was here \(authParam)")
return authParam
} catch _ {
print ("JSON Failure")
}
return nil
}
}()
let url : URL = {
return URL(string: Constant.baseURL)!
}()
var urlRequest = URLRequest(url: url)
// urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
// urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.httpMethod = method.rawValue
print("facebook was here = \(urlRequest.httpMethod!)")
let encoding = JSONEncoding.default
print("yahoo was here \(params)")
//let facejsonData = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions())
return try encoding.encode(urlRequest, with: params!)
}
}
And, I call the API using the following function:
Alamofire.request(WINAPIRouter.create(params, nil)).responseJSON
I think response from API is not in JSON, try to use URL encoding like below,
Alamofire.request(path, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil) . responseString(completionHandler: { ( dataResponse ) in
/// print response
})