试图像函数一样传递字典作为参数

时间:2019-04-24 20:04:34

标签: ios swift dictionary codable weather-api

我正在尝试将字典作为函数中的参数传递。我目前正在构建一个小型天气应用。我遇到的问题是尝试获取和解析JSON数据。我之前已经做过Weather应用程序,并且使用过Alamofire,但是我想不再使用podfile。 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来自{​​{3}}。下面是获取当前位置的函数。

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。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

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

正确的代码行应如下所示

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