Search code examples
iosswift3alamofire

how to check "Success" key value in swift 3.0


Alamofire.request(webpath).responseJSON
{   response in
    //here check success key ???
}

my json response contains

{Message = "some message";
Success = True;}

how to take Success key directly from response and check in if condition ? that it is true or false


Solution

    1. First you have to get the Result object from the response. It is an enum that can either be success or failure.
    2. Then you have to cast the Any object returned from the success value as a dictionary.
    3. Now you can simply access the property by its key.

    Like following:

    Alamofire.request(webpath).responseJSON { response in
        guard case .success(let rawJSON) = response.result else {
            // handle failure
            return
        }
    
        // rawJSON is your JSON response in an `Any` object.
        // make a dictionary out of it:
        guard let json = rawJSON as? [String: Any] else {
            return
        }
    
        // now you can access the value for "Success":
        guard let successValue = json["Success"] as? String else {
            // `Success` is not a String
            return
        }
    
        if successValue == "True" {
            // do something
        } else {
            // do something else
        }
    }