该应用在后台时,当与蓝牙设备断开连接时会收到回调,之后应用需要等待一段时间(1分钟),然后执行一些代码。如果屏幕打开,则该应用即使在后台也可以正常工作。但是如果屏幕关闭,则计时器不起作用,应用程序无法按预期执行。
以下是在AppDelegate中启动后台计时器的代码:
以下是在AppDelegate中启动后台计时器的代码:
func startTimerWith(timeInterval: TimeInterval) {
registerBackgroundTask()
timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: false, block: { (timer) in
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "Time"), object: nil)
self.endBackgroundTask()
})
}
func registerBackgroundTask() {
backgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
self.endBackgroundTask()
})
}
func endBackgroundTask() {
print("Background task ended.")
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
timer?.invalidate()
timer = nil
}
当与BLE设备断开连接时,我会通过注册后台任务来启动计时器:
func disconnected(_ peripheral: CBPeripheral, with error: Error?) {
print("DISCONNECTED!!!")
AppDelegate.sharedApp().startTimerWith(timeInterval: TimeInterval(TIME))
BLEDeviceHandler.sharedInstance.handleBLEDevice(connectedPeripheral!)
}