2017-07-25 110 views
0

我试图在用户接受位置跟踪时为其设置动画。该代码在他们已经接受位置跟踪然后加载视图时起作用,但是我希望在按位置跟踪接受时重新加载视图。当用户允许位置跟踪时更新位置

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

您可以使用:

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

嘿我添加了代码,但功能似乎不被调用。 –

+0

啊,对不起!我编辑了这篇文章。这是旧的快速。它应该是func locationManager(_ manager:CLLocationManager,didChangeAuthorization status:CLAuthorizationStatus){} –

+0

谢谢!它现在可以工作,但我可以使它对当前位置有动画效果吗? –

0

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

这将立即自动拨打您的CLLocationManagerDelegate方法异步requestLocation函数执行完毕。