我的Custom类中的私有常量:
private let locationManager = CLLocationManager()
在viewDidLoad()
中的我称之为方法:
private func setupLocationManager() {
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
但是当我稍后询问位置时:
println("-----\(locationManager.location)")
我明白了:
-----nil
问题出在哪里?我在设备上运行它。我的应用程序可以使用位置...
答案 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()
}
}