当用户允许位置跟踪时更新位置

Update location when user allows location tracking

我正在尝试动画显示用户在接受位置跟踪时所在的位置。该代码在他们已经接受位置跟踪然后加载视图时有效,但我希望在他们按下接受位置跟踪时重新加载视图。

override func viewDidLoad() {
    super.viewDidLoad()


    //Prepare to get User
     if CLLocationManager.authorizationStatus() != .authorizedAlways {
         // May need to change to support location based notifications
        locationManager.requestAlwaysAuthorization()
        print("hello")

        mapView.setVisibleMapRect(mapView.visibleMapRect, animated: true)
     }else {
        locationManager.startUpdatingLocation()
     }
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest

    mapView.delegate = self

}

动画到用户位置代码

//Get user location
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    //Show the map at the users current location
    let location = locations[0]
    let span:MKCoordinateSpan = MKCoordinateSpanMake(0.02,0.02 )
    let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
    mapView.setRegion(region, animated: true)
    self.mapView.showsUserLocation = true

    locationManager.stopUpdatingLocation()


 }

您可以使用:

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch status {
    case .notDetermined:
        locationManager.requestAlwaysAuthorization()
        break
    case .authorizedWhenInUse:
        locationManager.startUpdatingLocation()
        break
    case .authorizedAlways:
        locationManager.startUpdatingLocation()
        break
    default:
        break
    }
}

CLLocationManager 中用于更新位置的所有方法都是异步的,因此无论您的代码实现如何,用户允许位置访问到实际发生的位置更新可能会有延迟。

但是,通过在 locationManager(didChangeAuthorizationStatus) 中调用 CLLocationManager().requestLocation(),您可以确保在接受位置使用之前尽可能收到位置更新。

func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    switch status {
    case .notDetermined:
        locationManager.requestAlwaysAuthorization()
    case .authorizedWhenInUse:
        locationManager.requestLocation()
    case .authorizedAlways:
        locationManager.requestLocation()
    default:
        break
    }
}

这将在异步 requestLocation 函数完成执行后立即自动调用您的 CLLocationManagerDelegate 方法。