iOS Swift CLLocationManager无法获得准确的位置

时间:2016-10-20 08:54:17

标签: ios swift2 location cllocationmanager

我的iOS应用程序遇到了一些问题。在大多数情况下,我获取用户当前位置的代码运行良好,但有时它显示当前位置离当前位置非常远,甚至在国外。

我的viewDidLoad方法中的代码:

    manager = CLLocationManager()
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()

处理位置变更的功能

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    Swift.print(locations[0].coordinate.longitude)
    Swift.print(locations[0].coordinate.latitude)
    manager.stopUpdatingLocation()

}

请指导我做什么,以便每次都能正确获取用户的位置。我正在使用Swift 2。

1 个答案:

答案 0 :(得分:0)

您需要使用此代码,使用能够获取位置的后台模式和前台模式。

Swift 2.2

locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 100
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.startMonitoringSignificantLocationChanges()
if #available(iOS 9.0, *) {
    locationManager.allowsBackgroundLocationUpdates = true
}
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()

我希望这会对你有所帮助。你需要避免使用kCLLocationAccuracyBest,因为它会快速耗尽设备电池。所以设置特定的距离过滤器然后它会对你有用。

相关问题