如何请求启动 startUpdatingLocation?

How to request a start for startUpdatingLocation?

我在使用以下代码打开视图时启动位置管理器:

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

    var userLocation: CLLocation = locations[0] as! CLLocation

    userLatitude = userLocation.coordinate.latitude
    userLongitude = userLocation.coordinate.longitude

    if (userLocation.horizontalAccuracy < 80) {

        manager.stopUpdatingLocation()

    } else {

        addMapRegionAndAnnotation()

    }

}

所以这意味着如果在 80 米半径内检测到位置,locationManager 就会停止。 现在,如果我按下 updateLocation 按钮,我想再次启动此 locationManager:

@IBAction func updatePostMapView(sender: AnyObject) {

    manager.startUpdatingLocation()

}

然后应用程序会更新用户位置,直到半径再次小于 80 米... 但正如您所料,这不起作用,因为我无法从 locationManager 外部调用 manager.startUpdatingLocation()。

有没有人有解决办法?

您可以从任何方法内部调用 startUpdatingLocation() 或 stopUpdatingLocation()。首先,您必须在 class、

中创建位置管理器
class

let locationManager = CLLocationManager()

func initializeLocationManager()
{

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
    locationManager.pausesLocationUpdatesAutomatically = false
    locationManager.distanceFilter=kCLLocationAccuracyNearestTenMeters


}
func anyMethod()
{
   locationManager.stopUpdatingLocation()
   locationManager.startUpdatingLocation()
}