2017-07-25 114 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函數執行完畢。