Swift - 如何获取OpenWeatherMap JSON数据?

时间:2016-03-02 17:18:21

标签: ios json swift weather-api openweathermap

以下应用应获取用户的当前位置,然后使用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!)

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

1 个答案:

答案 0 :(得分:3)

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

如果您在plist中进行设置 - 在.plist文件中的NSAppTransportSecurity字典下将NSAllowsArbitraryLoads键设置为YES - 那么它可以正常工作。