【问题标题】:Having trouble appending value from JSON Parsing to array in Swift无法将 JSON Parsing 中的值附加到 Swift 中的数组
【发布时间】:2021-04-24 19:42:43
【问题描述】:

我正在玩https://jsonplaceholder.typicode.com,我正在尝试创建一个专辑列表。我尝试关注the example here,但专辑标题列表未显示在 TableView 上。我错过了什么?

class AlbumTableVC: UITableViewController {

var albums = [Album]()

override func viewDidLoad() {
    super.viewDidLoad()
    fetchAlbums()
}

func fetchAlbums() {
    AF.request("https://jsonplaceholder.typicode.com/albums").responseJSON { (response) in
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            
            for value in json.arrayValue {
                let id = value.dictionaryValue["id"]!.int
                let userId = value.dictionaryValue["userId"]!.int
                let title = value.dictionaryValue["title"]!.string
                
                let album = Album(id: id, userId: userId, title: title)
                self.albums.append(album)
            }
        case .failure(let error):
            print(error)
        }
    }
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return albums.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "AlbumCell", for: indexPath)
    
    let album = albums[indexPath.row]
    cell.textLabel?.text = album.title
    
    return cell
}}

【问题讨论】:

    标签: swift uitableview swifty-json jsonplaceholder


    【解决方案1】:

    在(异步)填充数据源后,您必须重新加载表格视图

    for value in json.arrayValue {
        let id = value.dictionaryValue["id"]!.int
        let userId = value.dictionaryValue["userId"]!.int
        let title = value.dictionaryValue["title"]!.string
        
        let album = Album(id: id, userId: userId, title: title)
        self.albums.append(album)
    }
    self.tableView.reloadData()
    

    考虑放弃SwiftyJSON,转而使用Codable。甚至 Alamofire 也支持它。

    看看这个简化的代码,你只需让Album 采用Decodable

    struct Album : Decodable { ...
    
    AF.request("https://jsonplaceholder.typicode.com/albums").responseDecodable { (response : DataResponse<[Album],AFError>) in
        switch response.result {
        case .success(let value):
            self.albums = value
            self.tableView.reloadData()
            
        case .failure(let error):
            print(error)
        }
    }
    

    【讨论】:

    • 哇哦。 reloadData 之前我也遇到过同样的问题,但这次我完全忘记了使用它。谢谢!
    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2019-01-02
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多