我正在构建一个小型的Weather应用程序,该应用程序正在访问openweathermap API
。我正在使用JSONDecoder
来解析JSON
中的API
。在大多数情况下,我能够在simulator
中获取大部分数据。除了应该显示在屏幕上的UIImage
之外。图像位于image.xcassets
中。下面是结构。
import UIKit
import CoreLocation
struct WeatherData: Codable {
let coord: Coord
let weather: [Weather]
let base: String
let main: Main
let visibility: Int
let wind: Wind
let clouds: Clouds
let dt: Int
let sys: Sys
let id: Int
let name: String
let cod: Int
}
struct Clouds: Codable {
let all: Int
}
struct Coord: Codable {
let lon, lat: Double
}
struct Main: Codable {
let temp: Double
let pressure, humidity: Int
let tempMin, tempMax: Double
// enum CodingKeys: String, CodingKey {
// case temp, pressure, humidity
// case tempMin = "temp_min"
/ / case tempMax = "temp_max"
// }
}
struct Sys: Codable {
let type, id: Int
let message: Double
let country: String
let sunrise, sunset: Int
}
struct Weather: Codable {
let id: Int
let main, description, icon: String
}
struct Wind: Codable {
let speed: Double
let deg: Int
}
通过JSON
访问的代码如下:
private func getWeatherData(parameters: [String : String]) {
guard let lat = parameters["lat"],
let long = parameters["long"],
let appID = parameters["appid"] else { print("Invalid parameters"); return }
var urlComponents = URLComponents(string: "https://api.openweathermap.org/data/2.5/weather")!
let queryItems = [URLQueryItem(name: "lat", value: lat),
URLQueryItem(name: "lon", value: long),
URLQueryItem(name: "appid", value: appID)]
urlComponents.queryItems = queryItems
guard let url = urlComponents.url else { return }
URLSession.shared.dataTask(with: url) { ( data, response, err ) in
DispatchQueue.main.async { // never, never, never 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)
print(city)
//self.updateWeatherData(city)
self.weatherData.description = city.weather[0].main
self.weatherData.temperature = Int(city.main.temp - 273)
self.weatherData.city = city.name
self.weatherData.condition = city.weather[0].id
WeatherDataModel().updateWeatherIcon(condition: self.weatherData.condition)
self.updateUIWeatherData()
} catch {
print(error)
self.cityLabel.text = "Connection issues"
}
}
}.resume()
}
和在模拟器上显示数据的函数是:
func updateUIWeatherData() {
cityLabel.text = weatherData.city
temperatureLabel.text = String(weatherData.temperature)
decriptionLabel.text = String(weatherData.description)
weatherIcon.image = UIImage(named: weatherData.weatherIconName)
}
我看过此警告的其他示例,但不确定该应用程序的含义。 Example of result of call is unused。 任何帮助将不胜感激。
答案 0 :(得分:1)
在我看来,你想要这行
self.weatherData.weatherIconName = WeatherDataModel().updateWeatherIcon(condition: self.weatherData.condition)
代替
WeatherDataModel().updateWeatherIcon(condition: self.weatherData.condition)
警告是说您正在计算weatherIcon
,但未将其分配给任何内容(您的weatherData
变量)