我正在编写一个每n分钟需要位置更新的应用程序,即使应用程序处于后台模式,也会将数据发送到服务器。关于这个任务,我经历了很多链接。正如我发现正确的解决方案是使用计时器并将其作为后台任务。
关于这一点,我有两个问题:
答案 0 :(得分:2)
在appdelegate里面创建像这样的方法
func getLocation()
{
locationManager.allowsBackgroundLocationUpdates = true
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
didFinishLaunchingWithOptions
方法
var n = 10 //seconds
var timer = Timer.scheduledTimer(timeInterval: n, target: self, selector: #selector(getLocation), userInfo: nil, repeats: true)
设置cllocationmanager的委托方法
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
//get the coordinates or do some code
}
答案 1 :(得分:2)
使用以下代码。这将有效3分钟
调用此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
}
//做你想做的事
func displayAlert{
}