[英]fatal error: unexpectedly found nil while unwrapping an Optional value
I am attempting to parse a JSON document and enter its information into a UICollectionView. 我正在尝试解析JSON文档,并将其信息输入到UICollectionView中。 I had tested the parsing before working on the UICollectionViewDelegate/Flowlayout/DataSource etc. It was returning the correct information, however now I am getting this error.
在处理UICollectionViewDelegate / Flowlayout / DataSource等之前,我已经测试了解析。它返回了正确的信息,但是现在我收到此错误。 Any idea what I am doing wrong here?
知道我在这里做错了吗?
class ViewModel {
let urlString = "https://s3.amazonaws.com/nxtapnxtap/clubsinfo.json"
var clubNames = [String]()
var smImg = [UIImage]()
var lgImg = [String]()
func fetchItems(success: () -> ()) {
let url = NSURL(string: urlString)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithURL(url!) { (data, response, error) in
var jsonError: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as NSDictionary // Error here --> fatal error: unexpectedly found nil while unwrapping an Optional value
if let unwrappedError = jsonError {
println("jsonError: \(unwrappedError)")
} else {
self.clubNames = json.valueForKeyPath("entry.name.label") as [String]
self.smImg = json.valueForKeyPath("entry.smimg.label") as [UIImage]
self.lgImg = json.valueForKeyPath("entry.lgimg.label") as [String]
success()
}
}
task.resume()
}
The object coming back from JSONObjectWithData is nil. 从JSONObjectWithData返回的对象为nil。 You are trying to force cast it as an NSDictionary.
您正试图将其强制转换为NSDictionary。 You need to check if it can be cast to an NSDictionary before you act on it:
您需要先对其进行检查,然后才能将其强制转换为NSDictionary:
func fetchItems(success: () -> ()) {
let url = NSURL(string: urlString)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithURL(url!) { (data, response, error) in
var jsonError: NSError?
if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as? NSDictionary {
self.clubNames = json.valueForKeyPath("entry.name.label") as [String]
self.smImg = json.valueForKeyPath("entry.smimg.label") as [UIImage]
self.lgImg = json.valueForKeyPath("entry.lgimg.label") as [String]
success()
} else if let unwrappedError = jsonError {
println("jsonError: \(unwrappedError)")
}
}
task.resume()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.