我收到错误:Use of unresolved identifier 'json'
从这一行开始:if let parseJSON = json {
这是与错误相关的代码片段
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()
}
}
我查看了这个问题:Swift : Use of unresolved identifier 'json'但我不知道如何解决我的问题或将变量放在json
答案 0 :(得分:1)
我认为你打算写if let parseJSON = jsonResult
,但无论如何都不会有效,因为do
中声明的变量只在该范围内可见。您需要在do
内移动相关代码。您可以将JSONSerialization的结果直接分配给parsJSON
。
您还应将此行var resultValue:String = parseJSON["status"] as String!
更改为var resultValue:String = parseJSON["status"] as! String
像这样修改你的代码:
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()
}
}