该应用程序在后台,它会在与 BLE 设备断开连接时收到回调,之后应用程序必须等待一段时间(1 分钟)然后执行一些代码。如果屏幕打开,即使在后台,应用程序也会按预期运行。但如果屏幕关闭,则计时器无法正常工作,并且应用程序无法按预期执行。
这是 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!)
}