Swift 位置返回 nil

Swift location comes back nil

此代码之前可以正常运行,但现在一直崩溃,因为返回的位置为 nil。我不确定此错误的来源或修复方法。据我所知,我的代码是正确的。有帮助吗?

import UIKit
import CoreLocation
import MapKit

class LocationController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    var locationManager = CLLocationManager()

    @IBOutlet var Map: MKMapView!

    var manager:CLLocationManager!
    var myLocations: [CLLocation] = []

        override func viewDidLoad()
        {
            super.viewDidLoad()

            self.Map.mapType = MKMapType.Standard
            self.Map.showsUserLocation = true

            //self.Map.removeAnnotations(self.theMap.annotations)

            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()


            let location = self.locationManager.location

            var latitude: Double = location.coordinate.latitude
            var longitude: Double = location.coordinate.longitude

            println("current latitude :: \(latitude)")
            println("current longitude :: \(longitude)")
        }

CLLocationManagerlocation属性声明为:

@NSCopying var location: CLLocation! { get }

因此您的 let location 可以用 nil 值填充。也许这个声明最近发生了变化,因为 Apple 清理了与可选相关的接口。

您需要绑定 latitudelongitude,同时尊重可能的 nil