【问题标题】:Swift - How to get OpenWeatherMap JSON Data?Swift - 如何获取 OpenWeatherMap JSON 数据?
【发布时间】:2016-06-15 16:52:28
【问题描述】:

以下应用应获取用户的当前位置,然后使用 OpenWeatherMap 显示该位置的名称和温度。

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var location: UILabel!
    @IBOutlet weak var temperature: UILabel!

    var locationManager: CLLocationManager = CLLocationManager()
    var startLocation: CLLocation!

    func extractData(weatherData: NSData) {
        let json = try? NSJSONSerialization.JSONObjectWithData(weatherData, options: []) as! NSDictionary

        if json != nil {
            if let name = json!["name"] as? String {
                location.text = name
            }

            if let main = json!["main"] as? NSDictionary {
                if let temp = main["temp"] as? Double {
                    temperature.text = String(format: "%.0f", temp)
                }
            }
        }
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let latestLocation: AnyObject = locations[locations.count - 1]

        let lat = latestLocation.coordinate.latitude
        let lon = latestLocation.coordinate.longitude

        // Put together a URL With lat and lon
        let path = "http://api.openweathermap.org/data/2.5/weather?lat=\(lat)&lon=\(lon)&appid=2854c5771899ff92cd962dd7ad58e7b0"
        print(path)            

        let url = NSURL(string: path)

        let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
            dispatch_async(dispatch_get_main_queue(), {
                self.extractData(data!)
            })
        }

        task.resume()
    }

    func locationManager(manager: CLLocationManager,
        didFailWithError error: NSError) {

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        startLocation = nil
    }
}

我一直在学习如何按照本教程从 OpenWeatherMap 获取数据: https://www.youtube.com/watch?v=r-LZs0De7_U

应用程序在以下位置崩溃:

self.extractData(data!)

因为 data 等于 nil,所以这不应该发生,因为当我将打印的路径复制并粘贴到我的 Web 浏览器中时,数据就在那里。我确定我正确地遵循了教程,那么问题是什么,我该如何解决?

【问题讨论】:

  • 一如既往:如果 API 提供 error 参数首先检查该参数并处理错误。如果dataTaskWithURL发生错误,data就是nil,如果没有错误,error就是nildata有效。 从不从网络接收数据时强制解包选项。
  • 我明白,但是在这种情况下,为什么我一开始就没有得到数据。
  • 再次:处理错误,我猜这是 ATS(应用程序传输安全)问题。
  • @vadian 我不应该这样做,因为这通常不应该发生。跳到视频的 16:34,由于快速更新,我的代码是相同的吧。为什么它对他有用,但对我不起作用?
  • 你似乎对建议免疫:你得到什么错误?

标签: ios json swift weather-api openweathermap


【解决方案1】:

问题在于传输安全 - 这给我们很多人带来了问题。这是解释如何解决它的 SO 答案之一Transport security has blocked a cleartext HTTP

如果您在 plist 中进行设置 - 在 .plist 文件中的 NSAppTransportSecurity 字典下将 NSAllowsArbitraryLoads 键设置为 YES - 然后就可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 2016-09-02
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    相关资源
    最近更新 更多