Search code examples
phpiosjsonswiftnsjsonserialization

Trying to Parse JSON in swift but not working


I'm trying to parse some JSON, this is what it's returning when I directly go to the URL:

[{"Password":"whatever1"}]

My code is able to receive the data correctly (when I debugged the variable "data" had the above JSON) however when trying to Parse it, it won't work. I think it might have to do with the square brackets, cause I've been parsing other JSONs without the square brackets and it works well.

Here is my code:

func SignIn (username: String, password: String, completion: @escaping (Bool)->())
{
    let url = URL(string: "http://<myIP>/API/SignIn.php?username=\(username)");

    let task = URLSession.shared.dataTask(with: url!)
    { (data, response, error) in
        if let data = data
        {
            do
            {
                // Convert the data to JSON
                let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]

              //  print( jsonSerialized)
                if let json = jsonSerialized, let result = json["Password"]
                {
                    print(result)
                    if (String(describing: result) == password)
                    {
                        completion(true)
                    }
                    else
                    {
                        completion(false)
                    }
                    // TODO: password is wrong,
                    // TODO: username is wrong
                    // TODO: else if timeout
                }
            }
            catch let error as NSError {
                print(error.localizedDescription)
                completion(false)
            }
        }
        else if let error = error
        {
            print(error.localizedDescription)
            completion(false)
        }
    }
    task.resume()

}

Solution

  • Rewrite code to :

    let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [[String : Any]]
    

    This is needed as your JSON response is an array of dictionaries, like the others have mentioned.

    Access the result using:

    let result = json.first["Password"]