【问题标题】:NSTimer in background, then resuming (Swift)NSTimer 在后台,然后恢复(Swift)
【发布时间】:2015-08-06 19:42:55
【问题描述】:

假设我有一个名为 number 的变量

var number: Int = 100

如果我有一个 NSTimer 每秒获取一个数字变量,并且用户关闭应用程序... 20 秒,当用户回到应用程序时,我如何才能获得新的数字变量在后台运行 20 秒后?

【问题讨论】:

  • 只是一个快速的想法,但也许您可以使用应用程序委托中的方法来记录应用程序进入后台和前台的时间,然后相应地更新您的变量。
  • 事实上@thefredelement 回答了您的问题,最好使用应用程序委托方法来了解您的应用程序何时进入后台并唤醒并计算两次之间经过的时间,因为在您的如果您不能让 NSTimer 在后台运行超过 180 秒 ~

标签: swift nstimer


【解决方案1】:

仅基于绝对时间,而不是基于本地重新计算。如果您需要刻度(例如更新屏幕计数器),那么:

var timer: NSTimer?
var timerStartTime: NSTimeInterval = 0.0

func startTimer() {
    timer = NSTimer(... to call myself every second ...)
    timerStartTime = NSDate.timeIntervalSinceReferenceDate()
}

func timerCallback(timer: NSTimer!) {
    let timeSinceTimerBegan = NSDate.timeIntervalSinceReferenceDate() - timerStartTime

    print("It has now been \(timeSinceTimerBegan) seconds since timing began; 
                                        counter should be at \(100 - timeSinceTimerBegan)")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多