jgravois
jgravois

Reputation: 2579

swift 4: Unable to parse JSON response

I am VERY NEW to Swift and IOS developing ...

I am using Alamofire and SwityJSON to post to an API endpoint for authentication and I am purposely entering wrong credentials to code an indication to the user.

Alamofire.request(API_URL, method: .post, parameters: parameters)
            .responseJSON {
            response in
            if response.result.isSuccess {
                let rspJSON: JSON = JSON(response.result.value!)

                if JSON(msg.self) == "Invalid Credentials" {
                    let alert = UIAlertController(title: "Error", message: "Those credentials are not recognized.", preferredStyle: UIAlertControllerStyle.alert)
                    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:{(action) in self.clearLogin()}))

                    self.present(alert, animated: true, completion: nil)

                }
                else {
                    print(rspJSON)
                }
            }
            else {
                print("Error \(response)")
            }
        }

The output of print(rspJSON) is

{ "msg" : "Invalid Credentials" }

so I would expect that the if JSON(msg.self) == "Invalid Credentials" conditional would hit but apparently it is not because the output of the print() statement is visible and no alert can be seen.

Any suggestions would be greatly appreciated.

Upvotes: 0

Views: 777

Answers (1)

Aryan Sharma
Aryan Sharma

Reputation: 635

While parsing your JSON, always find keys in response in the dictionary. Like in this case, you wanted value of 'msg', you have to parse using

if let message = res["msg"] as? String {}

as? String casts the response into the expected data type.

Alamofire.request(API_URL, method: .post, parameters: parameters).responseJSON {
        response in
        if let res = response.result.value as? NSDictionary {
            if let message = res["msg"] as? String {
                if message == "Invalid Credentials" {
                    let alert = UIAlertController(title: "Error", message: "Those credentials are not recognized.", preferredStyle: UIAlertControllerStyle.alert)
                    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:{(action) in self.clearLogin()}))
                    self.present(alert, animated: true, completion: nil)
                }
            }
        }
}

Upvotes: 1

Related Questions