带有URL的URLSession返回错误

时间:2018-07-18 19:51:52

标签: json swift weather urlsession

我已阅读有关SO的主题,但尚未找到答案。 我一直在尝试使用天气API为我的应用下载天气数据。奇怪的是,我可以在没有'?'的网址上运行它但是这个网址有一个'?'内置。我怀疑这是问题所在,但是如何解决或忽略它?无论如何,这是我的理论。代码如下:

struct WeatherData: Decodable {
    let description: String
    let temp: Double
    let wind: Double
}

func weather() {
    let url = "http://api.openweathermap.org/data/2.5/weather?q=London,GB?&units=imperial&APPID={40b5f59a0004885043fe3df3e0b6ed8e}"
    let urlObj = URL(string: url)

    URLSession.shared.dataTask(with: urlObj!) {(data, response, error) in

        do {
            let weatherObj = try JSONDecoder().decode([WeatherData].self, from: data!)
            print(data!)
            for weather in weatherObj {
                print(weather.temp, weather.description, weather.wind)

            }
        } catch {
            print("Got an Error")
        }

        }.resume()
}

因此按原样运行将产生错误:“线程1:致命错误:在展开可选值时意外发现nil”或URLSession行。

我遗漏了一些明显的东西还是有办法解决这个问题?

非常感谢

- 更新: 因此,在更改结构和{}之后,它一直有效,直到我开始将数据输入标签。这是最新的尝试:

func weather() {
    let lat = locationManager.location!.coordinate.latitude
    let long = locationManager.location!.coordinate.longitude

    //let baseURL = "http://api.openweathermap.org/data/2.5/weather?"
    let apiKey = "40b5f59a0004885043fe3df3e0b6ed8e"
    //let weatherURL = URL(string: "\(baseURL)lat=\(lat)&lon=\(long)&units=metric&APPID=\(apiKey)")
    let weahterURL = "http://api.openweathermap.org/data/2.5/weather?lat=\(lat)&lon=\(long)&units=metric&APPID=\(apiKey)"

    //let url = "http://api.openweathermap.org/data/2.5/weather?q=London,GB?&units=imperial&APPID=40b5f59a0004885043fe3df3e0b6ed8e"

    let urlObj = URL(string: weahterURL)

    URLSession.shared.dataTask(with: urlObj!) {(data, response, error) in

        do {
            let weatherObj = try JSONDecoder().decode(WeatherData.self, from: data!)
            print(weatherObj)
            //seems as though not gettign any data from beyond this point

            var desc = weatherObj.weather
            var wind = weatherObj.wind.speed
            var tempMin = weatherObj.main.temp_min
            var tempMax = weatherObj.main.temp_max

            DispatchQueue.main.async {
            self.weatherDesc = desc
            self.weartherWind.text = wind
            self.tempMinTxt.text = tempMin
            self.tempMaxTxt.text = tempMax
            }

        } catch {
            print("Got an Error", error.localizedDescription)
        }

        }.resume()
}

1 个答案:

答案 0 :(得分:2)

您错误地构造了网址,而不是

let url = "http://api.openweathermap.org/data/2.5/weather?q=London,GB?&units=imperial&APPID={40b5f59a0004885043fe3df3e0b6ed8e}"

let url = "http://api.openweathermap.org/data/2.5/weather?q=London,GB?&units=imperial&APPID=40b5f59a0004885043fe3df3e0b6ed8e"

{40b5f59a0004885043fe3df3e0b6ed8e}

应该是

40b5f59a0004885043fe3df3e0b6ed8e

您为解码器创建的结构无效,并且无法获取数据

//

struct WeatherData: Decodable {
   let weather: [WeatherItem]
   let wind: WindItem
   let main : MainItem
}

//

struct WeatherItem: Decodable {
   let description: String
}

//

struct WindItem: Decodable {
   let speed: Double
   let deg: Double
}

//

struct MainItem : Decodable {
   let tempMin: Double
   let tempMax: Double

   private enum CodingKeys: String, CodingKey {
        case tempMin = "temp_min" , tempMax = "temp_max"
    }

}

//

let weatherObj = try JSONDecoder().decode(WeatherData.self, from: data!)