ios - 加载数据后如何从完成块中获取整个数组
问题描述
我无法将数据数组返回到完成块
看一看:
我有从 API 获取数据的功能:
public func getCityWeather(completion: @escaping (Weather) -> ()){
for i in citiesGeo {
let urlString = "https://api.weather.yandex.ru/v2/forecast?lat=\(i.latitude)&lon=\(i.longitude)"
guard let url = URL(string: urlString) else {continue}
self.loadManager.getWeather(url: url) { (weather) in
completion(weather)
}
}
}
在这里得到它:
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.async { [self] in
weatherLoader.getCityWeather { (weather) in
print(weather)
}
}
}
没关系,但是我怎样才能将所有城市的天气放入数组中,然后将其发送到完成块中,这样我就可以从 ViewDidLoad 函数中获取它。
希望,你会有所帮助
解决方案
感谢@Don 的帮助。我回答我的问题。使用 DispatchGroup 可以完美地工作。下面我将显示代码
public func getCityWeather(completion: @escaping ([Weather]) -> ()){
DispatchQueue.global(qos: .userInitiated).async {
let downloadGroup = DispatchGroup() //create dispatch group
for i in self.citiesGeo {
downloadGroup.enter() //indicate that we enter
let urlString = "https://api.weather.yandex.ru/v2/forecast?lat=\(i.latitude)&lon=\(i.longitude)"
guard let url = URL(string: urlString) else {continue}
self.loadManager.getWeather(url: url) { (weather) in
self.citiesWeather.append(weather)
downloadGroup.leave() //indicate that task completed
}
}
downloadGroup.wait() //wait until all the "enter" find their "leave"
DispatchQueue.main.async {
completion(self.citiesWeather) //send array to completion block
}
}
}
推荐阅读
- laravel - Laravel 查询存在的几种
- java - 最近开始学习Java,我想创建一个计算点击次数的应用程序
- ios - 使用类和 swift 初始化程序快速编码、理解并更好地改进我的代码
- ajax - 数据不通过 formData 传输
- database - 如何为flutter windows应用程序实现数据库查询?
- javascript - 动态帮助命令 discord.js
- php - 如何将css存储到mysql数据库中并回调它以显示在html上
- java - 如果条件为真,一个方法是否可以阻止另一个方法被调用?
- android - 不推荐使用 toast.getView() 和 toast.setView()
- javascript - Javascript 数据映射