我正在使用Swift中的weatherApp,它从openweather.org请求一些数据,但是在将数据转换为模型数据时遇到了问题
数据模型类
import Foundation
class CurrentWeather {
let temperature: Int?
let tempMin: Int?
let tempMax: Int?
let location: String?
struct WeatherKeys {
static let temperature = "temp"
static let tempMin = "temp_min"
static let tempMax = "temp_max"
static let location = "name"
}
init(weatherDictionary: [String: Any]) {
temperature = weatherDictionary[WeatherKeys.temperature] as? Int
tempMax = weatherDictionary[WeatherKeys.tempMax] as? Int
tempMin = weatherDictionary[WeatherKeys.tempMin] as? Int
location = weatherDictionary[WeatherKeys.location] as? String
}
}
网络请求类别
import Foundation
import Alamofire
class WeatherService {
let APIKey = "c70ff4cc260c1075bbfb6849caa1ad29"
let weatherBaseURL = "http://api.openweathermap.org/data/2.5/weather?"
func getcurrentWeather(latitude: Double,longitude: Double,completion: @escaping (CurrentWeather?) -> Void) {
if let weatherURL = URL(string: "\(weatherBaseURL)lat=\(latitude)&lon=\(longitude)&appid=\(APIKey)") {
Alamofire.request(weatherURL).responseJSON(completionHandler: { (response) in
if let jsonDictionary = response.result.value as? [String: Any] {
if let currentWeatherDictionary = jsonDictionary["main"] as? [String: Any] {
//Print to show the data from the URL
print(currentWeatherDictionary)
//Initialize model data with currentWeatherDictionary(NOT WORKING)
let currentWeather = CurrentWeather(weatherDictionary: currentWeatherDictionary)
completion(currentWeather)
} else {
completion(nil)
}
}
})
}
}
}
当前WeatherDictionary的结果是 [“温度”:297.73,“温度最小”:294.15,“温度最大”:301.48,“湿度”:33,“压力”:1017]
我想使用数据模型将其值分配给它在viewController中的适当标签 目前,它没有显示我的temperatureLabel值,只是“-”
let coordinate: (lat: Double,long: Double) = (37.8267,-122.4233)
var weatherService = WeatherService()
override func viewDidLoad() {
super.viewDidLoad()
weatherService.getcurrentWeather(latitude: coordinate.lat,longitude: coordinate.long) { (currentWeather) in
if let currentWeather = currentWeather {
DispatchQueue.main.async {
if let temperature = currentWeather.temperature {
self.temperatureLabel.text = "\(temperature)"
} else {
self.temperatureLabel.text = "-"
}
}
}
}
}