这是我想在下载所有细节后执行的功能,以及下载后更新UIElements的另一个功能。此功能位于" CurrentWeather.swift"
内func downloadWeatherDetails(completed: ( () -> () )){
// tell Alimofire where to 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 kelvinToFarenhitePreDevision = (currentTemperature * (9/5) - 459.67 )
let kelvinToFarenhite = Double(round(10 * kelvinToFarenhitePreDevision/10))
self._currentTemp = kelvinToFarenhite
print(self._currentTemp)
}
}
}
}
completed()
}
}
此功能是更新UIEmelents
func updateMainUI(){
dateLabel.text = currentWeather.date
currentTempLabel.text = "\(currentWeather.currentTemp)"
currentWeatherTypeLabel.text = currentWeather.weatherType
locationLabel.text = currentWeather.cityName
currentWeatherImage.image = UIImage(named: currentWeather.weatherType)
}
这是在Override func viewDidLoad()
上调用它们 override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
currentWeather.downloadWeatherDetails { () -> () in
self.updateMainUI()
}
}
现在当我执行它不更新UI数据时 但它在控制台内打印
任何人都可以帮我解决这个问题
答案 0 :(得分:2)
您在请求完成前致电completed()
。
completed() //<- you need to call the completion handler inside the closure.
}
//completed() //<- this would be called before completion
}
我没有检查过代码的其他部分,但至少你需要解决这个问题。
答案 1 :(得分:0)
您的weatherDetails将异步下载。在viewDidLoad()内部,在收到并解析响应之前调用self.updateMainUI()。所以只需将UIUpdateMainUI()方法放在此块的末尾和内部:
if let dict = result.value as? Dictionary<String, AnyObject>{
}
如果您要求其他班级,请在那里设计协议。在要更新的viewController中对其进行符合。从上面的if-let块开始,在解析结束时,调用viewController的delegate方法进行更新。当然,在委托方法中,更新您的UI。 感谢。