简体   繁体   中英

Get value of json response swift

This is my code:

do {
   if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
   print(json)
   let success = json ["success"] as? Int
   print("Success: \(success)")

And this is my output:

{
    error = "Account does not exist, please create it!";
}
Success: nil

`

So, before let success = json ["success"] as? Int let success = json ["success"] as? Int , everything works well, but why is my output after this line nil ?

This is my php:

public function login($username,$password) {
        $query = "Select * from users where username = '$username' and password = '$password'";
        $result = mysqli_query($this->connection, $query);
        if (mysqli_num_rows($result) > 0) {
            $json['success'] = 'Welcome '. $username . '!';
            echo json_encode($json);
            mysqli_close($this->connection);
        } else {
            $json['error'] = 'Account does not exist, please create it!';
            echo json_encode($json);
            mysqli_close($this->connection);
        }

let success = json ["success"] as? Int

When you use this line it will extract the value of the key "success". As your json response does not contain that field it sets nil in the success variable.

Along with the error key you will need to return the success key too.

Success is nil because key 'success' does not exist in the JSON.

X as? Int X as? Int = try to make x an Int from X when possible. If not possible (because the value is nil or the value is not convertible to an Int ), make it Nil . That's what the question mark does.

So, I would do this:

if let success = json ["success"] as? Int {
    print("Success: \(success)")
} else {
    // Failed
}

You could also change your PHP code to make sure it always returns the 'success' key. However, I would recommend to use the Swift code above since you are always safe then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM