alamofire.error Code=-6006 "JSON could not be serialized

心不动则不痛 提交于 2019-12-28 04:18:08

问题


Been working on this for a bit with no success. I have a function that goes to a UIButton solely to perform alamofire calls to my rails api which uses all JSON.

I'm using Swift 2, Alamofire 3, XCode 7 & Rails 4 for my api which is deployed to Heroku

I keep getting this error when I fire off the function :

alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero length.

Here is my code :

@IBAction func Save(sender: AnyObject) {

    let postsEndpoint: String = "https://APIURL"
    let parameters = [
        "users": [
            "name": "James McHarty",
            "avatar": "Some binary data",
            "post": [
                "title": "First Test Post",
                "body": "This is the first test post for the API",
                "liked": "8", //will make INT later
                "img": "more binary data"
            ]
        ]
    ]

    Alamofire.request(.POST, postsEndpoint, parameters: parameters, encoding: .JSON)
        .responseJSON { response in
            guard response.result.error == nil else {
            // got an error in getting the data, need to handle it
            print(response.result.error!)
            return
        }

    }

    print("func'd")

}

回答1:


This is not Alamofire or swift error, The response returned by the server is not in the JSON format. you can print out response data and check what is wrong in this.

try this code to print out our server data to easily identifying to error and resolve this.

Alamofire.request("Your url").responseJSON(completionHandler: { (response) in
    switch response.result {
    case .success(let value):
        break

    case .failure(let error):
        print("\n\n===========Error===========")
        print("Error Code: \(error._code)")
        print("Error Messsage: \(error.localizedDescription)")
        if let data = response.data, let str = String(data: data, encoding: String.Encoding.utf8){
            print("Server Error: " + str)
        }
        debugPrint(error as Any)
        print("===========================\n\n")
    }

})



回答2:


The response returned by the server is not in the JSON format. You can use the tool to test the request first.

Print out of the error code is not a HTTP error code, because of the failure to resolve JSON




回答3:


You need to check the mimeType it will be "text/plain" instead of "application/json". That's why JSONSerialization class not able to parse the data.



来源:https://stackoverflow.com/questions/35374798/alamofire-error-code-6006-json-could-not-be-serialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!