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

标签 ios json swift parsing codable

我正在尝试在不使用 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/

相关文章:

json - 如何将 JSON 解码为 pandas 数据帧?

json - 如何将庞大的 Elisp 数据结构转换为 JSON?

ios - 如何在 Swift 4.0 中使用 DispatchQueue

swift - 长按手势操作表删除单元格

ios - 确定 iOS 应用程序是否通过 Siri 启动

ios - 继承函数

iOS:实现多个部分设置的最佳方式

ios - 传输安全已阻止明文 HTTP (XCode 8)

在 Linux/MAC 上无法识别 http 响应中的 JSON 编码的 unicode 但在 Windows 上?

iphone - SKPaymentQueue 崩溃于 'NotifyObserverAboutChanges'