我试图调用两个单独的api端点返回一些json,两个调用将对象添加到列表中...如何在将列表返回到视图控制器之前等待两个func完成
import Alamofire
import SwiftyJSON
class SearchService {
var searchItemList = [SearchItem]()
func performFetch(keyword: String, count: Int, completion:(items: [SearchItem]?) -> ()){
>>>// NEED TO WAIT FOR THE fetchItemsA AND fetchItemsB TO FINISH THEM RETURN ‘searchItemList’
}
func fetchItemsA(keyword: String, count: Int, completion:(error:NSError?) -> ()) {
guard let url = self.searchUrl else {
return
}
let manager = Manager.sharedInstance
manager.request(.GET, url, parameters: ["keywords": keyword, "count": count], encoding: ParameterEncoding.URL)
.validate()
.responseJSON {response in
…
for item in items {
self.searchItemList.append(SearchItem(json: item)!)
}
…
completion(error: resultError)
}
func fetchItemsB(keyword: String, count: Int, completion:(error:NSError?) -> ()) {
guard let url = self.searchUrl else {
return
}
let manager = Manager.sharedInstance
manager.request(.GET, url, parameters: ["keywords": keyword, "count": count], encoding: ParameterEncoding.URL)
.validate()
.responseJSON {response in
…
for item in items {
self.searchItemList.append(SearchItem(json: item)!)
}
…
completion(error: resultError)
}
}
任何帮助表示赞赏
答案 0 :(得分:1)
如果API不同,您可以尝试this answer。如果您想要执行两个异步请求,最简单的解决方案是计算请求并检查完成请求已完成的数量(答案中的第一个解决方案)。请记住,响应可能是成功或错误。