处理Alamofire的异步调用

时间:2017-06-17 17:47:42

标签: ios asynchronous swift3 xcode8 alamofire

我正在使用Swift 3和XCode 8

我是IOS开发和使用Swift的新手。我目前遇到的问题是,在异步调用成功完成后,某些必需的代码无法运行。

在我的常量文件中:

typealias DownloadComplete = () -> ()

在我的WeatherVC.swift文件中:

var currentWeather = CurrentWeather()

override func viewDidLoad() {
    super.viewDidLoad()
    TableView.delegate = self
    TableView.dataSource = self
    currentWeather.downloadWeatherDetails{
        //setup UI to load downloaded data
        print("Done 2")
        self.updateMainUI()
    }
}

在我的CurrentWeather.swift类中:

    func downloadWeatherDetails(completed: @escaping DownloadComplete){
    //Alamofire download
    let currentWeatherURL = URL(string: CURRENT_WEATHER_URL)!

    Alamofire.request(currentWeatherURL).responseJSON { response in
        let result = response.result
        if let dict = result.value as? Dictionary<String, AnyObject>{
            if let name = dict["name"] as? String{
                self._cityName = name.capitalized
                print(self._cityName)
            }

            if let weather = dict["weather"] as? [Dictionary<String, AnyObject>]{
                if let main = weather[0]["main"] as? String{
                    self._weatherType = main.capitalized
                    print(self._weatherType)
                }
            }

            if let main = dict["main"] as? Dictionary<String, AnyObject>{
                if let currentTemperature = main["temp"] as? Double {
                    let kelvinToCelsius = currentTemperature - 273.15
                    self._currentTemp = kelvinToCelsius
                    print(self._currentTemp)
                }
            }
        }
        print("Done 1")
    }
    completed() //Make sure to tell download is done

}}

当执行代码时,在“完成1”之前,首先打印出“完成2”,当我希望它是相反的方式时。

我该如何解决这个问题? (仅供参考:遵循Udemy的天气应用教程)

1 个答案:

答案 0 :(得分:0)

更新:只是在completed关闭内部移动responseJSON