gpt4 book ai didi

ios - 如何在同一个函数中只有 1 个完成处理程序用于 2 个 Alamofire 请求

转载 作者:可可西里 更新时间:2023-11-01 00:56:09 25 4
gpt4 key购买 nike

我有一个函数,里面有 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 - 如何在同一个函数中只有 1 个完成处理程序用于 2 个 Alamofire 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47949809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com