问题
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:
- 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?
- 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