我在从Weather Underground打印数据时遇到问题。我的代码适用于其他数据源,而不是Weather Underground。我甚至尝试用实际数据替换URL(即https://api.wunderground.com/api/APIKEY/forecast/geolookup/forecast/q/94129.json“),但它不会打印。
有关它可能是什么的任何建议?
import Foundation
import UIKit
class APIManager {
func weatherJSON(zip: String, completion: @escaping ([Weather]) -> Void) {
let baseUrlString = "https://api.wunderground.com/api/APIKEY/forecast/geolookup/forecast/q/\(zip).json"
guard let url = URL(string: baseUrlString) else { return }
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil, let data = data else { return }
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] else { return }
// MARK: Print JSON
print(json)
var weatherList = [Weather]()
for item in json {
if let weather = Weather.create(from: item) {
weatherList.append(weather)
}
}
completion(weatherList)
} catch {
print("Uh oh. You have an error with \(zip)!")
}
}
task.resume()
}
}
编辑:已解决
我使用了下面发布的代码,现在看到了错误。
答案 0 :(得分:1)
我建议将其更改为报告错误:
enum WeatherError Error {
case badURL
case invalidJSON
}
func weatherJSON(zip: String, completion: @escaping ([Weather]?, Error?) -> Void) {
let baseUrlString = "https://api.wunderground.com/api/APIKEY/forecast/geolookup/forecast/q/\(zip).json"
guard let url = URL(string: baseUrlString) else {
completion(nil, WeatherError.badURL)
return
}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil, let data = data else {
completion(nil, error)
return
}
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] else {
completion(nil, WeatherError.invalidJSON)
return
}
// MARK: Print JSON
print(json)
var weatherList = [Weather]()
for item in json {
if let weather = Weather.create(from: item) {
weatherList.append(weather)
}
}
completion(weatherList, nil)
} catch let parseError {
print("Uh oh. You have an error with \(zip)!")
if let responseString = String(data: data, encoding: .utf8) {
print("responseString = \(responseString)")
}
completion(nil, parseError)
}
}
task.resume()
}
然后,当你调用它时,你可以看到错误是什么
weatherJSON(zip: something) { weatherReports, error in
guard let weatherReports = weatherReports, error == nil else {
print(error)
return
}
// use weatherReports here
}
这不会解决您的问题,但它可以帮助您诊断问题所在。