我正在尝试进行API调用以从Web服务返回某些数据。我在每个ID的for循环中进行通话
代码是:
for data in bookMarkArray {
//get the bookMarkID
let bookMarkId: String = (data as AnyObject).value(forKey: "id") as! String
let APIURL = "XXXXXXXXXXXXXX/ArticleById?id=" + bookMarkId
let apiCall = APIManager.shared.fetchArticlesFromApi(API:APIURL)
let _ = apiCall.done {
articles -> Void in
self.certainArticle = articles
self.articlesDataSource.append(self.certainArticle[0])
//reload tableview after all bookmarks are fetched
if index + 1 == bookMarkArray.count {
self.tableView.reloadData()
}
else{
index = index + 1
}
}.catch {
error -> Void in
}
书签ID始终以相同的顺序排列(1-2-3)。但是,每次我打开控制器以查看表视图时,返回的文章都以不同的顺序排列。知道为什么会这样吗?
示例:
首次致电按以下顺序返回文章:1-2-3
第二次呼叫按以下顺序返回文章:2-1 -3
等
根据我发现的其他答案,我尝试按以下方式添加serialQueue:
let serialQueue = DispatchQueue(label: "queuename")
for data in bookMarkArray {
//get the bookMarkID
let bookMarkId: String = (data as AnyObject).value(forKey: "id") as! String
let APIURL = "XXXXXXXXXXXXXX/ArticleById?id=" + bookMarkId
serialQueue.sync {
let apiCall = APIManager.shared.fetchArticlesFromApi(API:APIURL)
let _ = apiCall.done {
articles -> Void in
self.certainArticle = articles
self.articlesDataSource.append(self.certainArticle[0])
//reload tableview after all bookmarks are fetched
if index + 1 == bookMarkArray.count {
self.tableView.reloadData()
}
else{
index = index + 1
}
}.catch {
error -> Void in
}
}
但不幸的是,它没有为我锻炼。有什么建议或解决方案吗?