gpt4 book ai didi

swift - 为什么我的 Weather Underground 数据没有在 Swift 3 中打印?

转载 作者:行者123 更新时间:2023-11-28 15:28:54 24 4
gpt4 key购买 nike

我在打印来自 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()
}
}

编辑:已解决

我使用了下面发布的代码,但现在发现错误。

最佳答案

我建议将其更改为报告错误:

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
}

这不会解决您的问题,但可以帮助您诊断问题所在。

关于swift - 为什么我的 Weather Underground 数据没有在 Swift 3 中打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44933194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com