class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var TableViewOutlet: UITableView!
let URL_GET_DATA = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=17.500010,78.461527&radius=1000&types=atm&key=AIzaSyA4G66cD6FTzU1UnLO2UHL2rpehzDNa2v4"
var icons = [Icon]()
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(URL_GET_DATA).responseJSON { response in
if let json = response.result.value {
let iconArray : NSArray = json as! NSArray
for i in 0..<iconArray.count{
self.icons.append(Icon(
name: (iconArray[i] as AnyObject).value(forKey: "name") as! String,
imageUrl: (iconArray[i] as AnyObject).value(forKey: "imageUrl") as! String
))
}
self.TableViewOutlet.reloadData()
}
}
self.TableViewOutlet.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return icons.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "one", for: indexPath)as? TableViewCell
let icon: Icon
icon = icons[indexPath.row]
cell?.nameOutlet.text = icon.name
Alamofire.request(icon.imageUrl).responseImage { response in
debugPrint(response)
if let image = response.result.value {
cell?.ImageOutlet.image = image
}
}
return cell!
}
}
我收到这样的错误
Could not cast value of type '__NSDictionaryI' (0x10a439508) to 'NSArray' (0x10a439008). 2018-09-27 17:42:43.020278+0530 TableViewJSON[14887:1123768] Could not cast value of type '__NSDictionaryI' (0x10a439508) to 'NSArray' (0x10a439008).
在第 30 行我收到一条错误消息
Thread1: signal SIGABRT
最佳答案
错误非常明显:json
是一个字典([String:Any]
),而不是一个数组。根本不要在 Swift 中使用 NSArray
– 以及可怕的 as AnyObject).value(forKey:
– !
并且始终有条件地绑定(bind)值以避免崩溃
...
if let json = response.result.value as? [String:Any], // <- Swift Dictionary
let results = json["results"] as? [[String:Any]] { // <- Swift Array
for result in results {
print(result["name"] as! String)
}
JSON 中根本没有关键的 imageURL
关于swift - 无法将类型 '__NSDictionaryI' 的值转换为 'NSArray',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52536876/