【发布时间】:2020-10-27 07:01:15
【问题描述】:
我正在努力从服务器获取UITableView 的数据和/或reloadData()。我正在创建这个应用程序来通过服务器检查用户的发音。数据解析结果很好(我检查了 print 语句),但它不会更新到我的表格单元格。
我创建了一个字典来存储加载的数据:
var summaryDict = ["Overall Score" : "Score", "Words" : "Score", "Syllables": "Score", "Phonemes": "Score"]
var summaryArray = ["Overall Score", "Words", "Syllables", "Phonemes"]
我也确实在解析 JSON 数据后更新了 dict 值:
.responseJSON { response in
switch response.result {
case .success:
do{
let json = try JSON(data: response.data!)
if let data = response.data {
if let summaryData = self.parseJSON(data) {
DispatchQueue.main.async {
print(summaryData)
self.summaryDict["Overall Score"] = summaryData.summaryScore
self.summaryDict["Words"] = summaryData.wordScore
self.summaryDict["Syllables"] = summaryData.syllableScore
self.summaryDict["Phonemes"] = summaryData.phoneScore
print(self.summaryDict)
self.delegate?.didUpdateScore(self, score: summaryData)
}
}
}
let statusJson = json["status"].string
if statusJson == "success" {
completion("success")
}
else { completion("error parseJSON") }
} catch {
print(error.localizedDescription)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
}
在我的 ViewController 上,我还添加了 tableview 数据源扩展:
extension FreeTrialViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return audioSender.summaryDict.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SummaryCell", for: indexPath) as! SummaryCell
cell.summaryLabel.text = self.audioSender.summaryArray[indexPath.row]
cell.summaryScore.text = self.audioSender.summaryDict[self.audioSender.summaryArray[indexPath.row]]
return cell
}
}
我尝试将reloadData() 放在任何我可以使用的地方或DispatchQueue.main.async 时不时地但单元格没有更新。
已编辑:在视图控制器中包含委托:
extension FreeTrialViewController: AudioSenderDelegate {
func didFailWithError(_ error: Error) {
print("parsing audio delegate error: \(error)")
}
func didUpdateScore(_ audioSender: AudioSender, score: SummaryData) {
// updateTable()
summaryTable.reloadData()
}
}
这是多次尝试后的最终结果: (当我拍照时,我错误地从数组的“总分”中删除了 1 个字符,因此总分消失了,但是当我更正它时,它变成了 4 个“分数”。 我想要的表:
Overall Score: 97
Words: 96.8
Syllable: 96.9
Phonemes: 97.0
已编辑:
我将在这里包含我调用表格的函数:
很确定 finish recording 里面是解析数据。
我确实尝试将guard 添加为:
guard audioSender.summaryDict["Words"] != "Score" else { return }
但它会出现空白。
【问题讨论】:
-
解析JSON数据后更新字典值后是否尝试过重新加载表视图数据?
-
是的,我在获取数据后更新了字典,就像我在第一个屏幕截图中包含的那样:
-
更新数据后,您需要使用更新的数据重新加载表。
-
我确实将
reloadData()函数放在了我的代表处,但它不起作用。我将它直接放在解析数据中但仍然无法正常工作。它应该放在哪里? :( -
@HàKiềuAnh,在
func didUpdateScore(_ audioSender: AudioSender, score: SummaryData)这个方法中,你是否可以获取数据或打印摘要数据以及检查方法是否被调用
标签: ios swift uitableview swift5