当我尝试运行这个项目时,我遇到了“使用未解析的标识符错误” . 这是我得到错误的代码
var jsonDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
as! NSDictionary
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if((error) != nil) {
print(error!.localizedDescription)
} else {
let err: NSError?
do {
var jsonDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
} catch {
if(err != nil) {
print("JSON Error \(err!.localizedDescription)")
}
else {
//5: Extract the Quotes and Values and send them inside a NSNotification
let quotes:NSArray = ((jsonDict.objectForKey("query") as! NSDictionary).objectForKey("results") as! NSDictionary).objectForKey("quote") as! NSArray
dispatch_async(dispatch_get_main_queue(), {
NSNotificationCenter.defaultCenter().postNotificationName(kNotificationStocksUpdated, object: nil, userInfo: [kNotificationStocksUpdated:quotes])
})
}
}
}
})
有人可以帮忙吗谢谢 .
3 回答
这个代码的蜘蛛网正是SwiftyJSON库存在的原因 . 我推荐它很高,它可以使用cocoapods导入到你的项目中 .
使用这个库得到的代码将是
这更具可读性,并且当您实现更多API时,速度更快 .
尝试以下: - (假设JSON具有根节点结构)
问题可能是
catch
块中的这行代码 .在上面的语句中
jsonDict
超出了范围 . 您在do
块中声明了jsonDict,但正在尝试在catch
块中使用它 .