Search code examples
iosswiftswift3

Get the JSON response from swift api call


I am bit new to swift programming with iOS. Can anyone help me to sort out the following problem. I am getting a JSON response as the following.

{
    "response": {
        "token": "d1fb8c33e401809691699fc3fa7dcb9b728dd50c7c4e7f34b909"
    },
    "messages": [
        {
            "code": "0",
            "message": "OK"
        }
    ]
}

I was trying several things to get the "token" out from this.

let data = json["response"] as! [[String : AnyObject]]

But none of these worked. Can anyone help me ? This is with swift 3


Solution

  • As response is a json object that has token so you need to cast response as dictionary then access token from it as below,

    if let response = json["response"] as? [String : Any],
       let token = response["token"] as? String {
          print(token)
    }
    

    Avoid using force-unwrapping that can cause crashes.


    Recommended way of parsing in Swift is using Codable. Here is the complete example,

    // MARK: - Result
    struct Result: Codable {
        let response: Response
        let messages: [Message]
    }
    
    // MARK: - Message
    struct Message: Codable {
        let code, message: String
    }
    
    // MARK: - Response
    struct Response: Codable {
        let token: String
    }
    
    do {
        let data = Data() // Change this to data from the API
        let result = try JSONDecoder().decode(Result.self, from: data)
        print(result.response.token)
    } catch {
        print(error)
    }