我正在尝试创建一个天气应用程序。我遵循了有关 JSON 和 Swift 4 Decodable 的教程,我遵循了该教程并且它有效。问题是,当我尝试使用自己的 URL 来发出请求时,它不起作用。 这是我的代码:
class MainVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let jsonUrlString: String = "https://api.darksky.net/forecast/APIKEY/37.8267,-122.4233"
private func getForecast(){
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
do{
let weatherForecast = try JSONDecoder().decode(Weather.self, from: data)
print(weatherForecast)
}catch _ as NSError{
}
}.resume()
}
}
错误日志:
Error Domain=NSCocoaErrorDomain Code=4864 "Expected to decode Array<Any> but found a dictionary instead." UserInfo={NSCodingPath=(
), NSDebugDescription=Expected to decode Array<Any> but found a dictionary instead.}
我如何解析这个 https://darksky.net/dev/docs#forecast-request ?我只需要 Daily 部分中的一些内容,但对我来说它就像一个数组中的数组。
最佳答案
看起来您的天气结构构建不正确。它应该看起来像这样:
struct DataItem: Codable {
var summary: String
var uvIndex: Int
}
struct Info: Codable {
var summary: String
var icon: String
var data: [DataItem]
}
struct Weather: Codable {
var daily: Info
var hourly: Info
var timezone: String
}
我遗漏了很多项目,但这应该可以帮助您入门。
关于JSON 请求未返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469641/