由于多个Alamofire请求,我想通过解析收到的JSON数据来填充表视图。然而,事情是每个单元格与其他单元格有不同的请求。每个单元格都基于IndexPath发出请求。由于调用是异步的,因此并非所有请求都已实现......
我的代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var name = ""
let url = "https://........"+items[indexPath.section][indexPath.row]+"......"
Alamofire.request(url).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
let object = swiftyJsonVar["results"][0]
print(object)
name = object["name"].stringValue
cell.textLabel?.text = name
}
}
return cell
}
如何实现每个请求?提前谢谢!
答案 0 :(得分:1)
您应该跟踪每个请求的挂钩索引路径,以便您知道返回的值是
struct Item
{
var indexPath:NSIndexPath!
func getData(index:NSIndexPath)
{
let url = "https://........"+items[indexPath.section][indexPath.row]+"......"
Alamofire.request(url).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
let object = swiftyJsonVar["results"][0]
globalArr// store indexpath and value
/// remove indexoath from allDownloads
/// send refresh to table
}
}
}
}
在行的单元格中
if(indexPath in globalArr)
{
// show it
}
else
{
// check whether it's download is in progress to avoid multiple same requests when scroll because of dequeuing
if(allDownloads doesn't contain inexpath)
{
// create object of item and start download
// allDownloads.add(object)
}
}
globalArr:跟踪所有下载的对象
allDownloads:跟踪正在进行的下载