user2498258 user2498258 - 1 month ago 110
iOS Question

Alamofire 4 URL Request parameter encoding to JSON

Recently upgraded to Alamofire 4 and running into few issues. Wondering how to encode the url request parameter to JSON in Alamofire Router. Here is the example I was following in Alamofire 3.

enum UserRouter: URLRequestConvertible {
static let baseURLString = "http://jsonplaceholder.typicode.com/"

case Get(Int)
case Create([String: AnyObject])
case Delete(Int)

var URLRequest: NSMutableURLRequest {
var method: Alamofire.Method {
switch self {
case .Get:
return .GET
case .Create:
return .POST

}
}

let params: ([String: AnyObject]?) = {
switch self {
case .Get:
return (nil)
case .Create(let newPost):
return (newPost)
}
}()

let url:NSURL = {
let relativePath:String?
switch self {
case .Get(let postNumber):
relativePath = "posts/\(postNumber)"
case .Create:
relativePath = "posts"
}

var URL = NSURL(string: PostRouter.baseURLString)!
if let relativePath = relativePath {
URL = URL.URLByAppendingPathComponent(relativePath)
}
return URL
}()

let URLRequest = NSMutableURLRequest(URL: url)

let encoding = Alamofire.ParameterEncoding.JSON
let (encodedRequest, _) = encoding.encode(URLRequest, parameters: params)

encodedRequest.HTTPMethod = method.rawValue

return encodedRequest
}
}


It seems now in Alamofire 4 this has been changed.

let encoding = Alamofire.ParameterEncoding.JSON
let (encodedRequest, _) = encoding.encode(URLRequest, parameters: params)


Here is what I am trying with Alamofire 4 Router, but not working as expected.

func asURLRequest() throws -> URLRequest {
let url = try UserRouter.baseURLString.asURL()

var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue


switch self {
case .updateDeviceToken(_,let device):
urlRequest = try ParameterEncoding.encode(urlRequest as URLRequestConvertible, with: device)
//urlRequest = try JSONEncoding.default.encode(urlRequest, with: device)
case .addUser(_, let user):
urlRequest = try URLEncoding.default.encode(urlRequest, with: user)
case .updateUser(_,_,let user):
urlRequest = try URLEncoding.default.encode(urlRequest, with: user)
case .lockUser(_,_,let user):
urlRequest = try URLEncoding.default.encode(urlRequest, with: user)
default:
break
}
return urlRequest

Answer

I use this encoding syntax:

...
method: .get,
parameters: parameters,
encoding: JSONEncoding.default,
headers: nil,
...

In your case, it could be like this:

let encoding = Alamofire.JSONEncoding.default

I was struggling with this issue too, until I found a simple example here:

https://github.com/Alamofire/Alamofire#json-encoding

Comments