Vah.Sah
Vah.Sah

Reputation: 532

Background location update every n minutes

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?

Upvotes: 1

Views: 4140

Answers (2)

Dhruv Narayan Singh
Dhruv Narayan Singh

Reputation: 655

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{


}

Upvotes: 2

Aravind
Aravind

Reputation: 1080

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
  }

Upvotes: 3

Related Questions