我正在尝试将数组作为 JSON api 的一部分进行访问。api 不是字典的一部分。我的功能如下:
func downloadJsonwithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSArray {
print(jsonObj!)
if let albumsArray = jsonObj! as? NSArray {
for album in albumsArray{
if let albumDict = album as? NSDictionary {
if let name = albumDict.value(forKey: "title") {
self.nameArray.append(name as! String)
}
if let name = albumDict.value(forKey: "artist") {
self.albumArray.append(name as! String)
}
if let name = albumDict.value(forKey: "thumbnail_image") {
self.imgURLArray.append(name as! String)
}
if let name = albumDict.value(forKey: "image") {
self.albumURLArray.append(name as! String)
}
}
}
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}).resume()
}
我得到的错误是
Non-optional expression of type 'NSArray' used in a check for optionals.
我怎样才能解决这个问题?任何帮助,将不胜感激。
在 if-let 绑定中,if let jsonObj = try? JSONSerialization.jsonObject
您将jsonObj
转换为 NSArray。因此, if-let:if let albumsArray = jsonObj! as? NSArray { }
是不必要的。您可以删除该行代码(以及相应的右花括号)并将其重命名jsonObj
为albumsArray
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句