尝试将函数中的字典作为参数传递

问题描述 投票:0回答:1

我试图将字典作为函数中的参数传递。我目前正在构建一个小天气应用程序。我遇到的问题是尝试获取并解析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。任何帮助,将不胜感激。

ios swift dictionary codable weather-api
1个回答
1
投票

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

正确的代码行应如下所示

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

© www.soinside.com 2019 - 2024. All rights reserved.