【发布时间】:2021-09-06 17:50:09
【问题描述】:
我正在使用 swift,我想接收温度和湿度数据,但我收到的只是零。我在另一个 swift 文件中有两个对象 temp 和 humdity。我在我的代码中做错了什么?不知道我错过了什么。
struct Weather: Codable {
var temp: Double?
var humidity: Int?
var name : String?
}
struct WeatherMain: Codable {
let main: Weather
}
ViewController
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var latitudeValue = Double()
var longitudeValue = Double()
@IBOutlet weak var humidityLabel: UILabel!
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
latitudeValue = locValue.latitude
longitudeValue = locValue.longitude
}
func retrieve() {
fetchWeather(lat: latitudeValue, lon: longitudeValue)
{ (response , error ) in
for res in response! {
print("Humid value is \(res.humidity ?? 0)")
}
}
}
@IBAction func showData(_ sender: Any) {
retrieve()
}
}
extension ViewController {
func fetchWeather(lat: Double, //Required
lon: Double,
completionHandler: @escaping ([Weather]?, Error?) -> Void) {
// MARK: Retrieve
let apikey = "45345345345343454Fake API"
/// create URL
let baseURL = "https://api.openweathermap.org/data/2.5/weather?lat=\(lat)&lon=\(lon)&appid=\(apikey)"
let url = URL(string: baseURL)
print("this is the url for weather : \(url!)")
/// Creating request
var request = URLRequest(url: url!)
request.setValue("Bearer \(apikey)", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let err = error {
print(err.localizedDescription)
}
do {
/// Read data as JSON
let json = try JSONSerialization.jsonObject(with: data!, options: [])
/// Main dictionary
guard let resp = json as? NSDictionary else { return }
/// weather
guard let weatherDic = resp.value(forKey: "weather") as? [NSDictionary] else { return }
let weatherData = try? JSONDecoder().decode(WeatherMain.self, from: data!)
var weatherList: [Weather] = []
/// Accessing each weather
for weatherObject in weatherDic {
if let weatherData = weatherData {
var weather = weatherData.main
//print("This is the temp \(weather.temp!)")
//print("This is the humidity \(weather.humidity!)")
weather.temp = weatherObject.value(forKey: "temp") as? Double
weather.humidity = weatherObject.value(forKey: "humidity") as? Int
weather.name = weatherObject.value(forKey: "name") as? String
weatherList.append(weather)
}
}
completionHandler(weatherList, nil)
} catch {
print("Caught error")
completionHandler(nil, error)
}
}.resume()
}
}
【问题讨论】:
-
您能告诉我
WeatherMain和Weather是什么吗?可能您没有正确解析 HTTP 响应。 -
是的,我现在就编辑它
-
顺便说一句,我确实得到了扩展中的值,但是当我尝试获取 ViewController 中的值时,我得到了 nil。
-
不要
try?。在开发过程中永远不要try?。抓住error并打印出来。 DecodingErrors 非常具有描述性。 -
您同时使用
JSONSerialization和JSONDecoder?做出选择...添加日志,告诉我们您的代码发生了什么,调用了什么,没有调用什么?
标签: swift xcode api openweathermap