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

时间:2017-07-25 12:18:55

标签: ios swift mkmapview cllocation

我正在尝试设置用户在接受位置跟踪时的位置。代码在他们已经接受位置跟踪然后加载视图时工作,但我希望在他们按位置跟踪接受时重新加载视图。

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


 }

2 个答案:

答案 0 :(得分:2)

您可以使用:

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
    }
}

答案 1 :(得分:0)

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

但是,通过在CLLocationManager().requestLocation()内拨打locationManager(didChangeAuthorizationStatus),您可以确保收到的位置更新尽可能接近位置使用情况。

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

一旦异步CLLocationManagerDelegate函数完成执行,这将自动调用requestLocation方法。