Background location update every n minutes

梦想的初衷 提交于 2019-12-25 09:26:32

问题


I'm writing an application that requires location updates every n minutes and sends data to a server even when the application is in background mode. I have gone through so many links about this task. As I found the proper solution is to use a timer and make it as a background task.

Concerning to this I have two questions:

  1. How can I implement these regular background location updates? I understand that Apple allows background tasks for an only certain time. So how can I make long-running background timer?
  2. Will apple reject the application with such kind of logics?

回答1:


inside appdelegate create method like this

      func getLocation()
      {
              locationManager.allowsBackgroundLocationUpdates = true
              locationManager.delegate = self
              locationManager.desiredAccuracy = kCLLocationAccuracyBest             
              locationManager.startUpdatingLocation()
      }

inside didFinishLaunchingWithOptions method in appdelegate

var n = 10 //seconds

var timer = Timer.scheduledTimer(timeInterval: n, target: self, selector: #selector(getLocation), userInfo: nil, repeats: true)

set the delegate method for cllocationmanager

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
  {
    locationManager.stopUpdatingLocation()
    locationManager.delegate = nil
    //get the coordinates or do some code
  }



回答2:


Use following code.This will work for 3 minutes

Call this didenterbackground or foreground

var time = 180
func applicationDidEnterBackground(_ application: UIApplication)
    {

        self.doBackgroundTask()
    }

 var timerBack  = Timer()
    func doBackgroundTask() {

        DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
            self.beginBackgroundUpdateTask()

              print("Background time remaining = \(UIApplication.shared.backgroundTimeRemaining) seconds")

            self.timerBack = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AppDelegate.displayAlert), userInfo: nil, repeats: true)
            RunLoop.current.add(self.timerBack, forMode: RunLoopMode.defaultRunLoopMode)
            RunLoop.current.run()

            self.endBackgroundUpdateTask()
        }
    }
    var backgroundUpdateTask: UIBackgroundTaskIdentifier!

    func beginBackgroundUpdateTask() {
        self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
            self.endBackgroundUpdateTask()
        })
    }

    func endBackgroundUpdateTask() {
        UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
        self.backgroundUpdateTask = UIBackgroundTaskInvalid
    }

//Do whatever you want

func displayAlert{


}


来源:https://stackoverflow.com/questions/41014848/background-location-update-every-n-minutes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!