我有一个函数,里面有 2 个 Alamofire 请求和一个完成处理程序。一旦我完成了从服务器下载数据的两个请求,我想重新加载我的collectionView。我在函数中有一个完成处理程序,但它被调用两次,这导致我的 collectionView 重新加载两次,而我只想重新加载一次。有什么办法可以做到这一点吗?非常感谢!
func getFeedVideos(completion: @escaping (_ completedDownloadVideo: Bool) -> ()){
Alamofire.request(youTubeUrl, method: .get, parameters: ["part":"snippet","maxResults": "20","nextPageToken" : "pageToken", "playlistId": playListId, "key": googleAPIKey], encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
guard let data = response.data else {return}
do {
let json = try JSONDecoder().decode(serverData.self, from: data)
self.dataFromAPI = json.items
completion(true)
} catch let jsonErr{
print(jsonErr)
}
}
Alamofire.request(youTubeChannelUrl, method: .get, parameters: ["part":"snippet", "key": googleAPIKey, "id": youTubeChannelId], encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
guard let data = response.data else {return}
do {
let json = try JSONDecoder().decode(channelInfo.self, from: data)
self.channelData = json.items
completion(true)
} catch let jsonErr{
print(jsonErr)
}
}
}
这是我在 ViewDidLoad 中调用该函数的方式
override func viewDidLoad() {
super.viewDidLoad()
getFeedVideos { (complete) in
if complete{
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
}
}
}
最佳答案
更好的解决方案
使用DispatchGroup
这是示例
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
Alamofire.request(youTubeUrl, method: .get, parameters: ["part":"snippet","maxResults": "20","nextPageToken" : "pageToken", "playlistId": playListId, "key": googleAPIKey], encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
guard let data = response.data else {return}
do {
let json = try JSONDecoder().decode(serverData.self, from: data)
self.dataFromAPI = json.items
completion(true)
} catch let jsonErr{
print(jsonErr)
}
dispatchGroup.leave()
}
dispatchGroup.enter()
Alamofire.request(youTubeChannelUrl, method: .get, parameters: ["part":"snippet", "key": googleAPIKey, "id": youTubeChannelId], encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
guard let data = response.data else {return}
do {
let json = try JSONDecoder().decode(channelInfo.self, from: data)
self.channelData = json.items
completion(true)
} catch let jsonErr{
print(jsonErr)
}
dispatchGroup.leave()
}
这是魔法线
dispatchGroup.notify(queue: .main) {
print("Both functions complete 👍")
}
Each call to enter() must be matched later on with a call to leave(), after which the group will call the closure provided to notify().
关于ios - 如何在同一函数中为 2 个 Alamofire 请求只有 1 个完成处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47949809/