【发布时间】:2019-09-15 06:43:29
【问题描述】:
我正在尝试在不使用 Podfiles 的情况下在 Swift 中创建天气应用程序,并且在将字典作为参数传递给解析 JSON 方面遇到了一个障碍。定位函数如下:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[locations.count - 1]
if location.horizontalAccuracy > 0 {
locationManager.startUpdatingLocation()
locationManager.delegate = nil
print("longitude = \(location.coordinate.longitude), latitude = \(location.coordinate.latitude)")
let latitude = String(location.coordinate.latitude)
let longitude = String(location.coordinate.longitude)
let params : [String : String] = ["lat" : latitude, "lon" : longitude, "appid" : APP_ID]
getWeatherData(url: WEATHER_URL, parameters: params)
}
}
为了解析 JSON,我创建了以下函数:
private func getWeatherData(url: String, parameters: [String : String]) {
let JsonURLString:[String: Any] = ["url": WEATHER_URL, "parameters": parameters]
print(JsonURLString)
guard let url = URL(string: JsonURLString) else { return }
URLSession.shared.dataTask(with: url) { ( data, response, err ) in
DispatchQueue.main.sync {
if let err = err {
print("Failed to get data from url:", err)
return
}
guard let data = data else { return }
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let city = try decoder.decode(WeatherData.self, from: data)
self.weatherData.city = city.name
} catch {
print(error)
self.cityLabel.text = "Connection issues"
}
}
}.resume()
}
我遇到的错误是guard let url = URL(string: JsonURLString) else { return } 行中的Cannot convert the value of type '[String: Any]' to expected argument type 'String' 行。我想知道我是否已经陷入困境,也许会使用另一种方法。我想在 Swift 4 中使用 codable,因为这应该是解析 JSON 的一种更简单的方法。现在在这个例子中,我不确定。任何帮助将不胜感激。
【问题讨论】:
-
您不能直接从字典中构建
URL。您的问题与您的 JSON 解析代码或使用 Codable 无关。您的问题是从字典创建 URL。 -
您应该使用
URLComponents从您拥有的所有部分构建 URL。 -
或者我应该重写这个函数并传入“Lat”和“Long”的坐标?比如
private func getWeatherData(Lat: Double, Long: Double)? -
我不熟悉 URLComponents 有什么好的资源吗?
-
参考文档和搜索。你会在这里找到很多例子。
标签: ios json swift parsing codable