一旦应用进入后台,如何继续使用计时器[重复]

问题描述 投票:0回答:1

我正在尝试执行一个简单的功能,该功能在应用程序的后台运行计时器。

简而言之,

  1. 应用程序启动后将启动10秒计时器
  2. 看到前景中的计时器已开始确认后,我锁定了设备
  3. 10秒后,在后台运行应用程序的情况下,我希望看到一条日志。当前在模拟器中有效,但不在设备上

下面的完整代码。 You can also download the app itself to try

[咨询了诸如as this之类的流行答案之后(还包含有关Timer是否在后台实际运行的矛盾答案),我并不完全是该主题上权威的答案。

感谢您的帮助。

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        var timer : Timer?
        if timer == nil {
            NSLog("Timer started")
            timer = Timer.scheduledTimer(withTimeInterval: 10, repeats: true, block: {_ in NSLog("After 10 seconds show up") //this will not work on a device
                //Also, I get the error: Can't end BackgroundTask: no background task exists with identifier 1 (0x1), or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.
            })
        }
    }
}
ios swift timer nstimer background-task
1个回答
1
投票
[顺便说一下,虽然that link描述了该过程,但它们的代码片段具有误导性。参见https://stackoverflow.com/a/23831862/1271826,以获得更现代的再现。
© www.soinside.com 2019 - 2024. All rights reserved.