我正在尝试获取UITableView标题以显示此处显示的输出打印json
https://i.imgur.com/yuOWW74.png
但是,当我运行程序时,输出显示 https://i.imgur.com/A00t6rE.png
我当前用于将数据导入标题对象的代码段是
String.format(Locale.getDefault(), "%,d %s", viewCount, "views")
我的tableviewcell类是
func fetchPlayerStats(completion: @escaping (Result<[beatMaps], Error>) -> ()) {
let urlString = "https://osu.ppy.sh/api/get_beatmaps?&k=983e993af59aa75b73d21cd42b4dfe96db068802"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, resp, err) in
if let err = err {
completion(.failure(err))
return
}
do {
let playerInfo = try JSONDecoder().decode([beatMaps].self, from: data!)
completion(.success(playerInfo))
} catch let jsonError {
completion(.failure(jsonError))
}
}.resume()
}
func start() {
fetchPlayerStats { (res) in
switch res {
case .success(let playerInfo):
playerInfo.forEach({ (info) in
print(info.title)
DispatchQueue.main.async {
self.titleLabel.text = info.title
}
})
case .failure(let err):
print("failed", err)
}
}
}
谢谢!
答案 0 :(得分:0)
您应该在vc中调用此方法,并创建一个数组作为表的dataSource,然后在回调中刷新它
var tableArr = [BeatMaps]() // start class/struct names with capital letter
func start() {
fetchPlayerStats { (res) in
switch res {
case .success(let playerInfo):
self.tableArr = playerInfo
DispatchQueue.main.async {
self.tableView.reloadData()
}
})
case .failure(let err):
print("failed", err)
}
}
}
当前,您为每个单元格多次加载数组,由于forEach
,它会将最后一项标题设置为tableView的标签
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! BeatMapCell
cell.label.text = tableArr[indexPath.row].title
return cell
}