【发布时间】:2017-11-20 07:32:33
【问题描述】:
我正在使用带有 XCode 8 的 Swift 3
我对 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
}}
在执行代码时,“Done 2”首先被打印出来,在“Done 1”之前,当我希望它是相反的时候。
我该如何解决这个问题? (仅供参考:遵循 Udemy 上的天气应用教程)
【问题讨论】:
-
您需要在
responseJSON闭包中调用completed,而不是在它之后。 -
哇,谢谢,现在可以使用了。
-
顺便说一句,这里并不重要,但与其在此处设置城市名称、天气类型和当前温度属性的属性,人们通常会将这三个解析值作为
DownloadComplete中的参数typealias,然后在您调用completed时将这些值传回。例如。typealias DownloadComplete = (_ city: String?, _ weather: String?, _ temperature: Float?, _ error: Error?) -> Void。执行网络请求的代码可能不应该与模型对象混在一起。您还希望让调用者决定要做什么并识别错误)
标签: ios asynchronous swift3 xcode8 alamofire