0
votes

I have a very simple Swift code to retrieve JSON data. But somehow it doesn't work properly.

Alamofire.request("*URL*").validate().responseJSON { response in
        print(response.result.value)
            if response.result.isSuccess {
               if let userList:[[String:Any]] = response.result.value as? [[String:Any]] {
                    for user:[String:Any] in userList {
                        if let userName = user["name"] as? String {
                            self._myList.append(User(name: userName, value: true))
                        }
                    }
                }
                self.tableView.reloadData()
            } else {
                print(response.result.error)
            }
    }

During the execution, I get this error message in the console :

Optional(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))

The print after calling Alamofire.request is showing "nil" in the console.

What I don't understand is it's working if I use .responseString instead of .responseJSON (but it shows only a String). I really need to use .responseJSON as I need to parse the result.

My JSON that appears on the web browser is very simple as well :

[{"name":"MrX","value":"0"}]

Any idea ?

Mika.

1

1 Answers

0
votes

use this

        import Alamofire
        import SwiftyJSON

        let baseURL: String = "http://baseURL.com"
        Alamofire.request(baseURL)
        .responseJSON { response in

            guard response.result.error == nil else {
                // got an error in getting the data, need to handle it
                print("error calling GET")
                print(response.result.error!)
                return
            }

            if let value = response.result.value {

                let json = JSON(value) // JSON comes from SwiftyJSON
                print(json) // to see the JSON response
                let userName = json["name"].array // .array comes from SwiftyJSON
                for items in userName! {
                  self._myList.append(User(name: items, value: true))
                }

                DispatchQueue.main.async {
                  self.tableView?.reloadData()
                }

            }
    }

and take the .validate() out, if you take that out you will see more detailed error description. Hope that helps.