Stephen Nyamweya
Stephen Nyamweya

Reputation: 114

JSON parse error from server when making request with Alamofire in swift 4

I need to make a post request to the api and obtain data from the response. The api returns the following response:

{
    valid: true
}

or

{
    valid: false
}

My Alamofire request looks something like this:

parameters = ["key": "somekey"]
let headers: HTTPHeaders = [
                "Content-Type": "application/json",
                "Authorization": "JWT \(token)"
            ]
Alamofire.request(baseURL, method: .post, parameters: parameters, headers: headers).responseJSON{
    response in
    if let result = response.result.value {
                        let JSON = result as! NSDictionary
                        print(JSON) //{ detail = "JSON parse error - Expecting value: line 1 column 1 (char 0)"}
                    }

I can't seem to be able to get the JSON data from the server to extract the value of valid. Instead I get the error: detail = "JSON parse error - Expecting value: line 1 column 1 (char 0)" from the server

Upvotes: 0

Views: 974

Answers (1)

Stephen Nyamweya
Stephen Nyamweya

Reputation: 114

Turns out I wasn't including one important parameter in the request encoding: JSONEncoding.default.(I guess the order matters) Here's what worked:

parameters = ["key": "somekey"]
let headers: HTTPHeaders = [
                "Content-Type": "application/json",
                "Authorization": "JWT \(token)"
            ]
Alamofire.request(baseURL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
                .responseJSON{
                    response in
                    if let result = response.result.value {
                        let JSON = result as! NSDictionary
                        print(JSON) //SUCCESS :{valid: 0}
                    }

Upvotes: 1

Related Questions