屏幕关闭/设备在iOS中被锁定时计时器未运行 [英] Timers not running when screen is turned off / device is locked in iOS

查看:381
本文介绍了屏幕关闭/设备在iOS中被锁定时计时器未运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该应用程序处于后台,并且在与BLE设备断开连接时收到回调,此后该应用程序必须等待一段时间(1分钟),然后执行一些代码.即使屏幕处于打开状态,该应用程序也能在预期的情况下正常运行.但是,如果关闭了屏幕,则计时器将无法运行,并且应用程序将无法按预期执行.

The app is in the background and it receives a callback upon disconnection with the BLE device, after which the app has to wait for sometime(1minute) and then execute some piece of code. The app behaves as expected even when in the background if the screen is turned on. But if the screen is turned off then the timer is not working and the app is not executing as expected.

这是AppDelegate中在后台启动计时器的代码:

This is the code in AppDelegate to start a timer in background:

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设备断开连接后,我通过注册到后台任务来启动计时器:

When disconnected from the BLE device, I start the timer by registering to background task:

func disconnected(_ peripheral: CBPeripheral, with error: Error?) {
    print("DISCONNECTED!!!")
    AppDelegate.sharedApp().startTimerWith(timeInterval: TimeInterval(TIME))
    BLEDeviceHandler.sharedInstance.handleBLEDevice(connectedPeripheral!)
} 

推荐答案

Bug已修复,因为应用程序使用了位置服务,但我忘记了当应用程序在后台时更新位置的权限.

Bug is fixed its because app using location services but I forgot to given permission to update location when app is in background.

这篇关于屏幕关闭/设备在iOS中被锁定时计时器未运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆