简体   繁体   English

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

[英]swift user location - update if move

So I have been able to get the users location via the following code.所以我已经能够通过以下代码获取用户位置。

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)")

  }

However I want to watch the users location and if they move update their location.但是我想观看用户的位置,如果他们移动更新他们的位置。

I am wondering how do I get this code to keep checking for the users location?我想知道如何获取此代码以继续检查用户位置?

My我的

override func viewDidLoad(){
  locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization()}

I get it popping up the request and I approve it but it does not run the code我得到它弹出请求并批准它但它不运行代码

Here is how you can get the location data.以下是获取位置数据的方法。 The code is similar to yours but with a bit of change and additions.该代码与您的相似,但有一些更改和添加。

First check if you already have user's permission to get their location data.首先检查您是否已获得用户获取其位置数据的权限。

    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
    }

If this method returns false you can ask for authorization.如果此方法返回 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
}

Finally in your CLLocationManagerDelegate implementation get the coordinates.最后在您的 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()
}

First, you have to check that you have user's permission to get their location data首先,您必须检查您是否有权获取用户的位置数据

func checkLocationServicesAuthorization() -> Bool {

         if CLLocationManager.locationServicesEnabled() {

            switch CLLocationManager.authorizationStatus() {
            case .notDetermined:

                 return false

            case .restricted, .denied:

             //code for open settings screen in user’s phone

                 return false

            case .authorizedWhenInUse, .authorizedAlways:

                 return true

            default:

                 return false

            }
        } else {

             //code for open settings screen in user’s phone

        }
        return false
    }

And

override func viewDidLoad() {

   super.viewDidLoad()

   locationManager = CLLocationManager()
   locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
   locationManager.delegate = self

}


override func viewDidAppear(_ animated: Bool) {

   super.viewDidAppear(animated)

   if checkLocationServicesAuthorization() {

      locationManager.startUpdatingLocation()

   } else {

      locationManager.requestWhenInUseAuthorization()
   }

}

You can use delegate method didUpdateLocations of CLLocationManagerDelegate and don't forgot to connect delegate yourLocationManager.delegate = self您可以使用CLLocationManagerDelegate委托方法didUpdateLocations并且不要忘记连接委托yourLocationManager.delegate = self

 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            let userLocation:CLLocation = locations[0] as CLLocation

            // Call stopUpdatingLocation() to stop listening for location updates, other wise this function will be called every time when user location changes.
            // yourLocationManager.stopUpdatingLocation()
            guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }

            let latitude = String.init(userLocation.coordinate.latitude)
            let longitude = String.init(userLocation.coordinate.longitude) 

            print("\(latitude), \(longitude)")

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM