使NSTimer在后台运行在物理设备上

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使NSTimer在后台运行在物理设备上相关的知识,希望对你有一定的参考价值。

我有一个我做过的计时器应用程序。

当我在模拟器上的iPhone X上运行它时,计时器将在后台运行正常,但是当我在我的物理设备(iPad Pro)上测试它时,它不会在后台运行。

  • 当我在后台说,我的意思是当你按下位于设备顶部(iPad)/侧面(iPhone)的关闭按钮时,屏幕变黑。

这是代表模拟器的故障,还是我不知道的事情,或者我需要改变一些关于我的应用程序的东西,以使其在后面的物理设备上工作?

谢谢

答案

在DidBackground中:

  1. 停止normalTimer。
  2. 启动新的backgroundTaskTimer

在WillForeground:

  1. 停止backgroundTaskTimer。
  2. 启动normalTimer

查找以下示例代码:

在Appdelegate:

宣言:

  var backgroundUpdateTask: UIBackgroundTaskIdentifier!

  var backgroundTaskTimer:Timer! = Timer()

执行:

func doBackgroundTask() {
    DispatchQueue.global(qos: .default).async {
        self.beginBackgroundTask()

        if self.backgroundTaskTimer != nil {
            self.backgroundTaskTimer.invalidate()
            self.backgroundTaskTimer = nil
        }

        //Making the app to run in background forever by calling the API
        self.backgroundTaskTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.startTracking), userInfo: nil, repeats: true)
        RunLoop.current.add(self.backgroundTaskTimer, forMode: RunLoopMode.defaultRunLoopMode)
        RunLoop.current.run()

        // End the background task.
        self.endBackgroundTask()

    }
}

func beginBackgroundTask() {
    self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(withName: "Track trip", expirationHandler: {
        self.endBackgroundTask()
    })
}

func endBackgroundTask() {
    UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
    self.backgroundUpdateTask = UIBackgroundTaskInvalid
}

在ApplicationDidEnterBackground中:

 func applicationDidEnterBackground(_ application: UIApplication) {

    //Start the background fetch
                self.doBackgroundTask()

        }

在ApplicationWillEnterForeground中:

func applicationWillEnterForeground(_ application: UIApplication) {

    if self.backgroundTaskTimer != nil {
        self.backgroundTaskTimer.invalidate()
        self.backgroundTaskTimer = nil
    }
}

以上是关于使NSTimer在后台运行在物理设备上的主要内容,如果未能解决你的问题,请参考以下文章

iOS 倒计时NSTimer

在后台运行 NSTimer 方法

当应用程序后台运行时,NSTimer 是不是会触发?

如何让我的应用在后台运行 NSTimer?

我们如何让 NSTimer 在 iOS 中为我​​的音频播放器在后台运行

如何在 iOS 7 中超过 180 秒的后台运行 NSTimer?