加载数据后如何从完成块中获取整个数组

How to get whole array from completion block after loading data

我无法将数据数组返回到完成块

看看:

我有从 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
         }
      
    }
}