Rodrigo Schreiner Rodrigo Schreiner - 3 months ago 115
JSON Question

Swift 3 problems Parsing json response

I am new on Swift but I was follwoing some examples like how to make a login app sending username and password fields to a php file and getting the json response back.

When I print my responseString I get:

[{"userid":1,"username":"rodrigo","password":"minhoca","groupname":"couple"}]

But when I try to parse the json I never can set the username variable because never gets into that part of the code, I just get "here"

Thanks for the help

func sendLoginInfo(username: String, password: String) -> String{
if let url = URL(string: "myphpurl"){
let request = NSMutableURLRequest(url:url)
request.httpMethod = "POST";// Compose a query string
let postString = "?username=\(myUsername)&password=\(myPassword)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with:request as URLRequest){
data, response, error in

if error != nil{
print("1\(error)")
}
else{
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("response string = \(responseString!)")
}

do {

if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {

// Print out dictionary
print(convertedJsonIntoDict)

// Get value by key
let firstNameValue = convertedJsonIntoDict["username"] as? String
print("here = \(firstNameValue!)")

}
else{
print("here")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
task.resume()
}
return ""
}

Answer

Change the NSDictionary to NSArray in your code because you are getting an array and trying to convert to dictonary:

 if let convertedJson = try JSONSerialization.jsonObject(with: data!, options: []) as? NSArray 

get the object at index 0 which will give you dictonary & then you can get username

So the Final code will be:

func sendLoginInfo(username: String, password: String) -> String{
    if let url = URL(string: "myphpurl"){
        let request = NSMutableURLRequest(url:url)
        request.httpMethod = "POST";// Compose a query string
        let postString = "?username=\(myUsername)&password=\(myPassword)"
        request.httpBody = postString.data(using: String.Encoding.utf8)
        let task = URLSession.shared.dataTask(with:request as URLRequest){
            data, response, error in

            if error != nil{
                print("1\(error)")
            }
            else{
                let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
              print("response string = \(responseString!)")
            }

            do {

                if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSArray {

                    // Print out dictionary
                    print(convertedJsonIntoDict)

                    // Get value by key
                    let firstNameValue = (convertedJsonIntoDict[0] as! NSDictionary)["username"] as? String
                    print("here = \(firstNameValue!)")

                }
                else{
                     print("here")
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        }
        task.resume()
    }
    return ""
}
Comments