我正在尝试解析JSON文档并将其信息输入到UICollectionView中。我在处理UICollectionViewDelegate / Flowlayout / DataSource等之前测试了解析。它返回了正确的信息,但是现在我收到了这个错误。知道我在这里做错了吗?
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()
}
答案 0 :(得分:2)
从JSONObjectWithData返回的对象是nil。您正试图将其强制转换为NSDictionary。在对其进行操作之前,您需要检查它是否可以转换为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()
}