1

以下应用程序应获取用户的当前位置,然后使用 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 浏览器中时,数据就在那里。我确定我正确地遵循了教程,那么问题是什么,我该如何解决?

4

1 回答 1

3

问题在于运输安全——这给我们很多人带来了问题。这是解释如何解决它的 SO 答案之一传输安全已阻止明文 HTTP

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

于 2016-03-02T17:57:04.437 回答