这是我的情景。我从openweather开始使用json api,然后创建一个带有一些属性的类Weather。在Weather天气实体中,我创建了一个名为downloadWeather
的函数来实际解析api然后我允许解析的值保存在属性中。
例如,self.max_temp = valueParsedFromJSON
。然后在MainViewController中,在ViewDidload中,我创建一个Weather的实例,即天气,调用函数downloadWeather,然后更新与weather.somproperty对应的ui标签。下载的内容打印到控制台(仅用于调试)很好,但它根本不会将内容呈现到ui中。是什么原因?这是我的实际代码:
var currentWeather:CurrentWeather!
// in MainViewControler.swift
// create weather instance to call downloadWeatherDetails function
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
currentWeather = CurrentWeather()
let completed = currentWeather.downloadWeatherDetails()
if completed == "completed" {
self.updateUI()
}
}
class CurrentWeather {
// this is CurrentWeather.swift where I save all the information in itself
var _cityName:String!
var _date:String!
var _weatherType:String!
var _currentTemp:Double!
var cityName: String {
if _cityName == nil {
_cityName = ""
}
return _cityName
}
var date: String {
if _date == nil {
_date = ""
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
let currentDate = dateFormatter.string(from: Date())
self._date = "Today, \(currentDate)"
return _date
}
var weatherType: String {
if _weatherType == nil {
_weatherType = ""
}
return _weatherType
}
var currentTemp: Double {
if _currentTemp == nil {
_currentTemp = 0.0
return _currentTemp
}
return _currentTemp
}
func downloadWeatherDetails(/*completed: DownloadComplete*/) -> String {
let currentWeatherURl:URL = 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 main = dict["main"] as? Dictionary<String, AnyObject> {
if let currentTempInKev:Double = main["temp"] as? Double {
let currentTempInCel = Double(round(currentTempInKev - 273.15))
self._currentTemp = currentTempInCel
}
}
if let weatherArr = dict["weather"] as? [Dictionary<String, AnyObject>] {
if let main = weatherArr[0]["main"] as? String {
self._weatherType = main.capitalized
}
}
if let name = dict["name"] as? String {
self._cityName = name
}
}
print(self.currentTemp)
print(self.weatherType)
print(self.cityName)
}
return "completed"
}
// the above works fine, but when called in MainViewController, properties is not rendered into UI
}
答案 0 :(得分:0)
要更新UI,您需要在主线程中设置UI控件的属性。 Alamofire
方法本质上是异步的,并且不会阻止主UI线程。将更新UILabels等的代码放在
DispatchQueue.main.async {
}
它应该有效