在Swift中将JSON解析的值附加到数组时遇到麻烦



我正在玩https://jsonplaceholder.typicode.com,我试图创建一个专辑列表。我试着遵循这里的例子,但专辑标题列表没有显示在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
}}

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

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)
}
}

最新更新