PHP Web Dev 101 PHP Web Dev 101 - 2 months ago 11
JSON Question

Use of unresolved identifier 'json'

I am receiving the error:

Use of unresolved identifier 'json'


from this line:
if let parseJSON = json {


This is the snippet of the code relevant to the error

let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in

if error != nil {
print("error=\(error)")
return
}
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
if let parseJSON = json {
var resultValue:String = parseJSON["status"] as String!;
print("Result: \(resultValue)")

if(resultValue=="Success")
{

//Login is sucessful
NSUserDefaults.standardUserDefaults().setBool(true,forKey:"isUserLoggedIn");
NSUserDefaults.standardUserDefaults().synchronize()

self.dismissViewControllerAnimated(true, completion: nil)

}

}

}

task.resume()

}

}


I reviewed this problem: Swift : Use of unresolved identifier 'json' but I do not know how I can fix my issue or where to put the variable of
json

Answer

I think you meant to write if let parseJSON = jsonResult but anyways that is not gonna work either since the variables declared in the do are only visible at that scope. you need to move relevant code inside the do. You can assign the result of JSONSerialization directly to parsJSON.

You should also change this line var resultValue:String = parseJSON["status"] as String! to var resultValue:String = parseJSON["status"] as! String

Modify your code like this:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
    data, response, error in

    if error != nil {
        print("error=\(error)")
        return
    }
    do {
        if let parseJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
            print(parseJSON)

            let resultValue:String = parseJSON["status"] as! String
            print("Result: \(resultValue)")

            if(resultValue=="Success")
            {
                //Login is sucessful
                NSUserDefaults.standardUserDefaults().setBool(true,forKey:"isUserLoggedIn");
                NSUserDefaults.standardUserDefaults().synchronize()

                self.dismissViewControllerAnimated(true, completion: nil)
            }
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }

}
task.resume()

}

}
Comments