2017-02-07 50 views
0

我正在開發一個應用程序,我需要定期更新用戶的位置,但是當應用程序暫停時我無法獲取位置更新或在後臺運行。我還啓用了背景位置更新功能。如何使用swift即使在應用程序在後臺運行時使用swift獲取位置更新

viewDidLoad中的代碼:

override func viewDidLoad() { 
     super.viewDidLoad() 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.allowsBackgroundLocationUpdates = true 
     locationManager.requestAlwaysAuthorization() 
     locationManager.requestWhenInUseAuthorization() 
     let user=FIRAuth.auth()?.currentUser?.displayName 
     if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse){ 
      locationManager.requestLocation() 
      location=locationManager.location 
      locationManager.startUpdatingLocation() 
      locationManager.startMonitoringSignificantLocationChanges() 
      //updating to database 
      ref.child("\(user!)/lat").setValue(location.coordinate.latitude) 
      ref.child("\(user!)/long").setValue(location.coordinate.longitude) 
      //location=locationManager.location 
     } 
} 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     location=locations[locations.count-1] 
    } 
+0

希望這個答案會幫助你http://stackoverflow.com/questions/5323634/ios-application-executing-tasks-in-background – iMuzahid

+0

我覺得這個環節有助於您 http://stackoverflow.com/questions/28503990/ios-running-background-task-for-update-user-location-using-swift – Ram

+0

@Prakhar兄弟你必須看看這個https://github.com/ voyage11 /位置 –

回答

0
啓用

位置更新 - >背景模式 - >能力

我用這種方法在背景得到的位置。在AppDelegate類這種方法寫

func getLocation() { 
    self.locationManager = CLLocationManager() 
    self.locationManager.delegate = self 
    if self.locationManager.responds(to: #selector(self.requestAlwaysAuthorization)) { 
     self.locationManager.requestAlwaysAuthorization() 
    } 
    self.locationManager.distanceFilter = kCLDistanceFilterNone 
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest 
    if !CLLocationManager.locationServicesEnabled() { 
      // location services is disabled, alert user 
     var servicesDisabledAlert = UIAlertView(title: "Alert", message: "Location service is disable. Please enable to access your current location.", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "") 
     servicesDisabledAlert.show() 
    } 
    else { 
     self.locationManager.startUpdatingLocation() 
    } 
} 
+1

@EricAya更新 –

相關問題