如何使用Alamofire的JSON数据填充tableview?

时间:2017-10-26 01:24:04

标签: json swift uitableview alamofire

在我陈述问题之前,我想让每个人都知道我是Swift编码环境的新手,所以请原谅我缺乏知识。目前,我无法根据从JSON URL返回的数据使用Alamofire填充tableview的单元格。当我在模拟器中运行应用程序时,数据显示在控制台中,但应用程序崩溃时出现SIGABRT错误。作为参考,我使用的是tableviewcontroller,而不是使用带有tableview元素的viewcontroller。这是我到目前为止的代码:

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
    }

3 个答案:

答案 0 :(得分:2)

发生崩溃是因为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

答案 1 :(得分:0)

好的,首先要改变

up.setAuthor(Upload_BookDetailsPage.uBookAuthor);
up.setBook_Name(Upload_BookDetailsPage.uBookName);

let cell = tableView.dequeueReusableCell(withIdentifier: "top10", for: indexPath)

但是,有了这个,let cell = tableView.dequeueReusableCell(withIdentifier: "top10") 将是cell,您必须返回cell?

接下来在你的Alamofire回复中,

cell!

为什么?

Alamofire请求是“异步”的,这意味着它会在您的应用正在执行其他操作时执行代码。因此,您可能在加载表后设置该数组,因此 if let json = response.result.value { print(json) self.responseArray = json as! NSArray self.reloadData() //If above line doesn't work, try tableView.reloadData() }

答案 2 :(得分:-1)

替换以下行

let cell = tableView.dequeueReusableCell(withIdentifier: "top10", for: indexPath)

let cell = tableView.dequeueReusableCell(withIdentifier: "top10")
相关问题