在我陈述我的问题之前,我想让每个人都知道我对Swift这个编码环境很陌生,所以请原谅我缺乏知识。目前,基于JSON返回的数据,我很难使用Alamofire填充表视图的单元格。当我在模拟器中运行应用程序时,数据会显示在控制台中,但是应用程序崩溃时会出现SIGABRT错误。作为参考,我使用的不是带有tableview元素的viewcontroller,而是使用tableview控制器。到目前为止,这是我的代码:
import UIKit
import Alamofire
class TableViewController: UITableViewController {
var responseArray: NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request("https://rss.itunes.apple.com/api/v1/us/apple-music/top-songs/all/10/explicit.json").responseJSON { response in
if let json = response.result.value {
print(json)
self.responseArray = json as! NSArray
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return responseArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "top10", for: indexPath)
// Configure the cell...
let whichSong = responseArray[(indexPath as NSIndexPath).row]
let artistName = (whichSong as AnyObject)["artistName"] as? String
cell.textLabel?.text = artistName
return cell
}发布于 2017-10-26 04:48:59
之所以会发生崩溃,是因为JSON的根对象是字典(由{}表示),而不是数组。
首先,将JSON字典的类型别名和数据源数组声明为本机类型,一个JSON字典数组:
typealias JSONDictionary = [String:Any]
var responseArray = [JSONDictionary]()然后解析JSON并重新加载表视图,您可能需要键results的数组
Alamofire.request("https://rss.itunes.apple.com/api/v1/us/apple-music/top-songs/all/10/explicit.json").responseJSON { response in
if let json = response.result.value as? JSONDictionary,
let feed = json["feed"] as? JSONDictionary,
let results = feed["results"] as? [JSONDictionary] {
print(results)
self.responseArray = results
self.tableView.reloadData()
}
}然后在cellForRow中显示数据
let song = responseArray[indexPath.row]
cell.textLabel?.text = song["artistName"] as? String发布于 2017-10-26 04:16:14
好的,那么首先换一次
let cell = tableView.dequeueReusableCell(withIdentifier: "top10", for: indexPath)至
let cell = tableView.dequeueReusableCell(withIdentifier: "top10") 但是,这样,cell将是cell?,您必须返回cell!。
接下来是你的阿拉莫火反应,
if let json = response.result.value {
print(json)
self.responseArray = json as! NSArray
self.reloadData()
//If above line doesn't work, try tableView.reloadData()
}为什么?
Alamofire请求是“异步的”,这意味着它在应用程序做其他事情时执行代码。因此,很可能是在加载表后设置该数组,因此reloadData()
发布于 2017-10-26 02:13:20
替换下面一行
let cell = tableView.dequeueReusableCell(withIdentifier: "top10", for: indexPath)使用
let cell = tableView.dequeueReusableCell(withIdentifier: "top10")https://stackoverflow.com/questions/46944409
复制相似问题