按下主页按钮后 NSTimer 不触发

NSTimer not firing after home button is pressed

我有一个 NSTimer 设置为每秒触发。使用模拟器,这将在我通过按下主页按钮离开应用程序后正确调用 eachSecond() 方法。但是,在真实的 iPhone 6 上,一旦我离开,直到再次打开应用程序时,才会再次调用 eachSeconds。

为什么这在真实设备上的表现可能不同?有没有办法确保它在这个用例中每秒触发一次?

它是一款健身应用,因此需要记录 phone 锁定或用户暂时离开时的持续时间。

谢谢,

lazy var timer = NSTimer()

fun init() {
   timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(RunViewController.eachSecond(_:)), userInfo: nil, repeats: true)
}

func eachSecond() {
 // update UI etc.
}

您需要将计时器添加到主 运行 循环中。

func init() {
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(RunViewController.eachSecond(_:)), userInfo: nil, repeats: true)

    NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}

当您的应用暂停时,NSTimer 不会触发。 XCode下运行后台执行不同;后台执行限制不适用。

为了确定您的应用暂停时已经过去了多少时间,您可以在 applicationDidEnterBackground 中存储一个时间戳,并根据 [=] 中保存的时间戳与当前时间之间的差异计算经过的时间12=]