解析JSON返回nil,为什么?

时间:2017-06-23 15:49:15

标签: ios json swift

这是我第一个使用JSON的项目,所以这个问题可能与同样情况下的其他人有关。 我正在使用DarkSky API制作天气应用程序。到目前为止,我正在从互联网请求数据,解析它,并进行测试,在控制台中打印它。不幸的是,我只是零。这是相关的代码:

- >我的ViewController中的函数:

func getWeatherData(latitude: String, longitude: String, time: String) {

    let basePath = "https://api.darksky.net/forecast/xxxxxxxxxxxxxxxb170/"
    let url = basePath + "\(latitude),\(longitude)"
    let request = URLRequest(url: URL(string: url)!)

    let task = URLSession.shared.dataTask(with: request) {
        (data:Data?, response:URLResponse?, error:Error?)
        in

        if let data = data {
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
                    let dictionary = json
                    UserDefaults.standard.set(dictionary, forKey: "lastWeatherUpdate")
                }
            } catch {
                print(error.localizedDescription)

            }

        }
    }


}

func getCurrentWeather() {
    getWeatherData(latitude: "37", longitude: "40", time: "40000")
    let weather = UserDefaults.standard.dictionary(forKey: "lastWeatherUpdate")

    print(weather?["latitude"])
}

有人发现我的错误吗?以下是DarkSky如何指定JSON数据的结构:

"latitude": 47.20296790272209,
  "longitude": -123.41670367098749,
  "timezone": "America/Los_Angeles",
  "currently": {
    "time": 1453402675,
    "summary": "Rain",
    "icon": "rain",
    "nearestStormDistance": 0,
    "precipIntensity": 0.1685,
    "precipIntensityError": 0.0067,
    "precipProbability": 1,
    "precipType": "rain",
    "temperature": 48.71,
    "apparentTemperature": 46.93,
    "dewPoint": 47.7,
    "humidity": 0.96,
    "windSpeed": 4.64,
    "windGust": 9.86,
    "windBearing": 186,
    "visibility": 4.3,
    "cloudCover": 0.73,
    "pressure": 1009.7,
    "ozone": 328.35

嗯,显然这只是JSON的重要部分。

有人能发现我的错误吗?

1 个答案:

答案 0 :(得分:0)

  

有人发现我的错误吗?

实际上有两个错误:

  • 如评论中所述,任务必须为resumed
  • dataTask异步工作,它需要一个完成处理程序才能在调用后打印一些东西。

为方便起见,代码使用带有关联类型的简单枚举作为返回类型。

enum WeatherResult {
    case success([String:Any]), failure(Error)
}

func getWeatherData(latitude: String, longitude: String, time: String, completion: @escaping (WeatherResult)->()) {

    let basePath = "https://api.darksky.net/forecast/xxxxxxxxxxxxxxxb170/"
    let urlString = basePath + "\(latitude),\(longitude)"
    let url = URL(string: urlString)!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

        if let error = error {
           completion(.failure(error))
           return 
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
                completion(.success(json))
            } else {
                completion(.failure(NSError(domain: "myDomain", code: 1, userInfo: [NSLocalizedDescriptionKey : "JSON is not a dictionary"])))
            }
        } catch {
            completion(.failure(error))
        }
    }

    task.resume()
}

func getCurrentWeather() {
    getWeatherData(latitude: "37", longitude: "40", time: "40000") { result in
        switch result {
        case .success(let dictionary):
            UserDefaults.standard.set(dictionary, forKey: "lastWeatherUpdate")
            print(dictionary["latitude"])
        case .failure(let error):
            print(error.localizedDescription)
        }
    }
}
相关问题