gpt4 book ai didi

ios - 无法将类型 '[String : Any]' 的值转换为预期的参数类型 'String'

转载 作者:行者123 更新时间:2023-11-28 13:42:28 26 4
gpt4 key购买 nike

我正在尝试在不使用 Podfile 的情况下在 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(字符串:JsonURLString) else { return } 。我想知道我是否掉进了兔子洞,也许使用了另一种方法。我想在 Swift 4 中使用 codable,因为这应该是一种更简单的解析 JSON 的方法。现在在这个例子中,我不确定。任何帮助将不胜感激。

最佳答案

试试这个代码。

JsonURLString is a [String: Any] type object not a String type. So you nee to convert it to a String type object.

private func getWeatherData(url: String, parameters: [String : String]) {
let JsonURLString:[String: Any] = ["url": WEATHER_URL, "parameters": parameters]
print(JsonURLString)
let urlString = JsonURLString["url"] as? String
guard let url = URL(string: urlString!) 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()
}

关于ios - 无法将类型 '[String : Any]' 的值转换为预期的参数类型 'String',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55855961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com