尝试像在函数中一样将字典作为参数传递

Trying to pass a dictionary as in a function as a parameter

我正在尝试将字典作为参数传递给函数。我目前正在构建一个小型天气应用程序。我遇到的问题是试图获取和解析 JSON 数据。我以前做过一个天气应用程序并使用过 Alamofire,但我想不再使用 podfiles。 Alamofire 的功能如下:

func getWeatherData(url: String, parameters: [String : String]) {
    Alamofire.request(url, method: .get, parameters: parameters).responseJSON {
        response in
        if response.result.isSuccess {
            print("Success! Got the weather data")
            let weatherJSON : JSON = JSON(response.result.value!)
            print(weatherJSON)
            self.updateWeatherData(json: weatherJSON)

        } else {
            print("Error \(String(describing: response.result.error))")
            self.cityLabel.text = "Connection Issues"
        }
    }
}

现在我想使用可编码和解码器来访问 JSON 数据。我遇到的问题是设置 JSONURLString 变量。

private func getWeatherData(url: String, parameters: [String : String]) {
    let JsonURLString:[String: String] = [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()
}

我使用的 API 来自 openweatherAPI 。下面是一个获取当前位置的函数。

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)

    }
}

问题是上述功能无法正常工作,因为我无法从 openweatherAPI 解析JSON。任何帮助将不胜感激。

let JsonURLString:[String: String]应该让JsonURLString:[String: Any],因为你的参数已经是字典了。

正确的代码行应该如下所示

let JsonURLString:[String: Any] = ["url": WEATHER_URL, "parameters": parameters]