[英]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. 我正在编写一个需要每n分钟更新一次位置的应用程序,即使该应用程序处于后台模式,它也会将数据发送到服务器。 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: 对此,我有两个问题:
inside appdelegate create method like this appdelegate内部的创建方法是这样的
func getLocation()
{
locationManager.allowsBackgroundLocationUpdates = true
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
inside didFinishLaunchingWithOptions
method in appdelegate 在appdelegate中的
didFinishLaunchingWithOptions
方法中
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 设置cllocationmanager的委托方法
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
//get the coordinates or do some code
}
Use following code.This will work for 3 minutes 使用下面的代码,它将持续3分钟
Call this didenterbackground or foreground 将此称为didenterbackground或前台
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{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.