Why after all the below code, after I do a po NSKeyedUnarchiver.unarchiveObject(with: (response.request?.httpBody)!)
I get nil
? And the response code is 400. And the reason the response code is 400, I believe is because of the parameters. Any suggestions why this happens?
let urlRequest = NSMutableURLRequest(url: url)
let bodyData = parameters.first!.key + "=" + String(describing: parameters.first!.value)
urlRequest.bind(to: command!)
urlRequest.httpBody = bodyData.data(using: .utf8)
urlRequest.httpMethod = "POST"
urlRequest.allHTTPHeaderFields = NetworkManager.defaultHeaders()
return Alamofire.request(urlRequest.copy() as! URLRequest)
EDIT: Ok, so I replaced some lines and now the code looks like this and the parameters are no longer nil:
let urlRequest = NSMutableURLRequest(url: url)
let dataParameters: Data = NSKeyedArchiver.archivedData(withRootObject: parameters)
urlRequest.bind(to: command!)
urlRequest.httpBody = dataParameters
urlRequest.httpMethod = HTTPMethod.post.rawValue
urlRequest.allHTTPHeaderFields = NetworkManager.defaultHeaders()
return Alamofire.request(urlRequest.copy() as! URLRequest)
But even like this I get a 400 code. So after investigating a little with postman I found that if I put the body like this {"xxxxx":"xxxxxxxxx"} it works and I get a good code, but if I use a key and value it doesn't. How do I make that work?
So I found why I got the bad request and the answer was really simple. Just had to use json serialization.
And I just replaced this
let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
urlRequest.httpBody = jsonData
with this
let dataParameters: Data = NSKeyedArchiver.archivedData(withRootObject: parameters)
urlRequest.httpBody = dataParameters
I'll just leave this here in case someone has the same problem as me.