【问题标题】:Cannot convert value of type '[String : Any]' to expected argument type 'String'无法将类型“[String:Any]”的值转换为预期的参数类型“String”
【发布时间】: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


【解决方案1】:

试试这个代码。

JsonURLString 是 [String: Any] 类型对象,而不是 String 类型。所以你需要把它转换成String类型的对象。

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()
}

【讨论】:

  • 干杯 Gregory 稍后会尝试。
猜你喜欢
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
相关资源
最近更新 更多