2017-06-17 127 views
0

我正在使用Swift 3和XCode 8處理Alamofire的異步調用

我對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 

}} 

當執行代碼「完成2「在」完成1「之前首先被打印出來,當我希望它是相反的。

我該如何解決這個問題? (FYI:關於Udemy的天氣應用程序教程)

+1

你需要把你的調用放到'responseJSON'閉包內的'completed',而不是放在它後面。 – Rob

+0

哇謝謝,它現在有效。 – Mat

+1

順便提一下,這裏並不重要,但是在這裏人們通常會將這三個解析的值作爲參數放在'DownloadComplete'' typealias'中,而不是在這裏設置城市名稱,天氣類型和當前臨時屬性的屬性,然後通過這些當你調用'completed'時返回值。例如。 'typealias DownloadComplete =(_ city:String?,_ weather:String?,_ temperature:Float?,_ error:Error?) - > Void'。執行網絡請求的代碼可能不應該混淆模型對象。您還想讓來電者決定要做什麼並識別錯誤) – Rob

回答

0

更新:它僅僅是在responseJSON閉合內移動completed