快速用户位置 - 如果移动则更新

Rus*_*wer 1 location ios swift

所以我已经能够通过以下代码获取用户位置。

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
      if status != .authorizedWhenInUse {return}
    print("test LOCATION BELOW")
      locationManager.desiredAccuracy = kCLLocationAccuracyBest
      locationManager.startUpdatingLocation()
      let locValue: CLLocationCoordinate2D = manager.location!.coordinate

        print("UUID: \(String(describing: uuid)) locations = \(locValue.latitude) \(locValue.longitude)")

  }
Run Code Online (Sandbox Code Playgroud)

但是我想观察用户的位置以及他们是否移动更新他们的位置。

我想知道如何获取此代码来继续检查用户位置?

我的

override func viewDidLoad(){
  locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization()}
Run Code Online (Sandbox Code Playgroud)

我收到它弹出的请求,我批准了它,但它不运行代码

Aya*_*mon 5

以下是获取位置数据的方法。该代码与您的代码类似,但有一些更改和添加。

首先检查您是否已获得用户获取其位置数据的权限。

    func isLocationServicesEnabled() -> Bool {
        if CLLocationManager.locationServicesEnabled() {
            switch(CLLocationManager.authorizationStatus()) {
            case .notDetermined, .restricted, .denied:
                return false
            case .authorizedAlways, .authorizedWhenInUse:
                return true
            @unknown default:
                return false
            }
        }

        return false
    }
Run Code Online (Sandbox Code Playgroud)

如果此方法返回 false,您可以请求授权。

// Initialize manager in your viewDidLoad
override func viewDidLoad() {
   super.viewDidLoad()

   locationManager = CLLocationManager()
   locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
   locationManager.delegate = self
   // Do other stuff
}


override func viewDidAppear(_ animated: Bool) {
   super.viewDidAppear(animated)
   // Check for auth
   if isLocationServicesEnabled() {
      locationManager.startUpdatingLocation()
   } else {
      locationManager.requestWhenInUseAuthorization()
   }
   // Do other stuff
}
Run Code Online (Sandbox Code Playgroud)

最后在 CLLocationManagerDelegate 实现中获取坐标。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
     guard let location = locations.last?.coordinate else { return }
     // Use location.latitude and location.longitude here
     // If you don't want to receive any more location data then call
     locationManager.stopUpdatingLocation()
}
Run Code Online (Sandbox Code Playgroud)