首页 > 解决方案 > 加载数据后如何从完成块中获取整个数组

问题描述

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

看一看:

我有从 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 函数中获取它。

希望,你会有所帮助

标签: iosswiftclosures

解决方案


感谢@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
         }
      
    }
}

推荐阅读