当被问到位置时,核心位置返回nil

时间:2015-05-28 09:43:24

标签: swift core-location

我的Custom类中的私有常量:

private let locationManager = CLLocationManager()
viewDidLoad()中的

我称之为方法:

private func setupLocationManager() {
    locationManager.delegate = self
    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()
}

但是当我稍后询问位置时:

println("-----\(locationManager.location)")

我明白了:

-----nil

问题出在哪里?我在设备上运行它。我的应用程序可以使用位置...

1 个答案:

答案 0 :(得分:0)

您不应该尝试以这种方式获取位置,因为获取位置可能需要一些时间(有关详细信息,请参阅GPS TTFF)。由于您的位置管理员已经拥有委托,您必须在didUpdateLocations委托方法中获取位置。在致电startUpdatingLocation

之前,请务必确保您拥有使用位置的权限
private func setupLocationManager() {
    locationManager.delegate = self
    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.desiredAccuracy = kCLLocationAccuracyBest

    if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways{

        locationManager.startUpdatingLocation()

    }else{
        locationManager.requestWhenInUseAuthorization()
    }
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!){

    println(manager.location)

}

func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

    if status == CLAuthorizationStatus.AuthorizedWhenInUse || status == CLAuthorizationStatus.AuthorizedAlways {

        locationManager.startUpdatingLocation()

    }
}