Swifui print value of data in response

Viewed 104

I am using a post API method like this

AF.request("http://40.86.255.119/api/Authentication", method:.post, parameters: parameters,encoding: JSONEncoding.default) .responseJSON { (response) in
     print(response)            
 }

It's showing me a response

success({
    data =     {
        security =         (
        );
        token = "eyJhbGc";

    };
    key = "<null>";
    message = "Login Successfully";
    succeed = 1;
})

I need to print just a token of data and need to know how can I do this?

Response screenshot by swagger

enter image description here

I try to like this but the issue is how ill show token that is inside the data array. It's showing a message which is outside an array but the token is inside an array.

AF.request("http://40.86.255.119/api/Authentication", method: .post,  parameters: parameters, encoding: JSONEncoding.default)
        .responseJSON { response in
            switch response.result {
            case .success(let value):
                if let json = value as? [String: Any] {
                    print(json)
                    print(json["message"]) //this work
                    print(json["data"]["token"]) //this didnt work
                }
            case .failure(let error):
                print(error)
            }
    }
1 Answers

I highly recommend to take advantage of the JSON decoding capabilities of AF.

Create two structs

struct Response : Decodable { let data : TokenData }
struct TokenData : Decodable { let token : String }

And replace .responseJSON with .responseDecodable and an appropriate type annotation of response.

In any case you should handle the potential error

AF.request("http://40.86.255.119/api/Authentication", method:.post, parameters: parameters) .responseDecodable { (response : DataResponse<Response,AFError>) in
    switch response.result {
       case .success(let result): print(result.data.token)
       case .failure(let error): print(error)
    }     
}
Related