I want to populate a table view by parsing JSON data received thanks to several Alamofire requests. However, the thing is that each cell has a different request from the others. Each cell makes a request based on IndexPath. Since the calls are asynchronous, not all requests are achieved...
My code:
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
}
How would it be possible to achieve every request? Thanks in advance!
You should keep track of hooking indexpath with every request so you know what the value returned is for
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
}
}
}
}
in cell for row
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: keep track of all downloaded objects
allDownloads : keep track of in progress downloads
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.