gpt4 book ai didi

ios - 屏幕关闭/设备在 iOS 中锁定时计时器不运行

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:29:16 26 4
gpt4 key购买 nike

应用程序在后台,它在与 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!)
}

最佳答案

这里有两点很重要:

  1. Timer doesn't work if the app is in background state for more than 10 minutes. I had an exact scenario where I had to perform some action in background. I found out that after 10 minutes, timer didn't work.
  2. Timers do not work when the device is locked. App gets suspended immediately once the device is locked. This is for iOS >= 7.0

关于ios - 屏幕关闭/设备在 iOS 中锁定时计时器不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50129279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com