简体   繁体   English

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

[英]Making NSTimer run in the background on a physical device

I have a timer app that I have made.我有一个我制作的计时器应用程序。

When I run it on the iPhone X on the simulator, the timer will run in the background just fine, but when I test it on my physical device (iPad Pro), it does not run in the background.当我在模拟器上的 iPhone X 上运行它时,计时器会在后台正常运行,但是当我在我的物理设备(iPad Pro)上测试它时,它不会在后台运行。

  • When I say in the background, I mean when you press the off button located on the top (iPad)/side (iPhone) of the device, so that the screen goes black.当我说在后台时,我的意思是当您按下设备顶部 (iPad)/侧面 (iPhone) 的关闭按钮时,屏幕会变黑。

Is this a glitch on the simulator's behalf, or something that I am not aware of, or is there something I need to change about my app to make it work in the background on PHYSICAL DEVICES as well?这是模拟器的故障,还是我不知道的问题,还是我需要更改我的应用程序以使其在物理设备的后台运行?

Thanks谢谢

In DidBackground:在 DidBackground 中:

  1. stop normalTimer.停止正常定时器。
  2. start New backgroundTaskTimer启动新的后台任务计时器

In WillForeground:在 WillForeground 中:

  1. stop backgroundTaskTimer.停止 backgroundTaskTimer。
  2. start normalTimer启动正常定时器

Find below sample code:找到以下示例代码:

In Appdelegate:在 Appdelegate 中:

Declaration:宣言:

  var backgroundUpdateTask: UIBackgroundTaskIdentifier!

  var backgroundTaskTimer:Timer! = Timer()

Implementation:执行:

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
}

In ApplicationDidEnterBackground:在 ApplicationDidEnterBackground 中:

 func applicationDidEnterBackground(_ application: UIApplication) {

    //Start the background fetch
                self.doBackgroundTask()

        }

In ApplicationWillEnterForeground:在 ApplicationWillEnterForeground 中:

func applicationWillEnterForeground(_ application: UIApplication) {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM