Kelvin Lau Kelvin Lau - 1 year ago 76
Swift Question

Translating Alamofire call to URLSession

I've got a old codebase that I'm trying to migrate out of. The network calls currently use Alamofire 4.0 and I'm trying to use

instead. I'm having trouble figuring out what's wrong, here's what I've been doing. I start off with the route and params that I want to post:

// route to user creation
let url = ...

let params = ["user": ["first_name": "John", "last_name": "Appleseed", "email": "", "password": "asdfgh"]]

Here's the old and new network calls:

// old network request
Alamofire.request(url, method: .post, parameters: newUser, encoding: JSONEncoding.default).responseJSON { response in
// ...

// new code
var request = URLRequest(url: url)
let jsonData = try! params, options: .prettyPrinted)
request.httpBody = jsonData
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { return print("error=\(error)") }

if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("status code should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")

let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")


For some reason, I'm getting a status code of 400 in my
attempt. Alamofire works fine.

Any advice appreciated.

Answer Source

The problem is that the request isn't recognized as a JSON call. Write the following assignment after you create your URLRequest:

request.allHTTPHeaderFields = ["Content-Type": "application/json"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download