Swift:在计算机处于睡眠状态时保持 NSTimer 运行 (OSX)

Swift: Keep NSTimer Running While Computer is Asleep (OSX)

我正在编写一个包含通用秒表计时器的 OS X 应用程序。我正在使用 NSTimer。我希望用户能够启动计时器并在很长一段时间(比如 30 分钟)后返回,并且计时器仍为 运行。问题是当计算机关闭或休眠时,我的计时器不会继续 运行,而且我不想让我的计算机长时间打开和打开。有几个关于此问题的线程涉及 iOS 应用程序,但 none(至少我发现)与 OS X 有关。有人知道这个问题的解决方法吗?例如,我试图模仿 iOS 随附的 "Clock" 应用程序的 "Stopwatch" 功能,除了笔记本电脑而不是 phone。 "clock" 应用程序中的秒表将继续 运行,即使 phone 长时间关闭也是如此。

我想出的方法并不是在后台实际 运行 NSTimer,而是找出应用程序进入后台之间经过了多少时间当它重新成为焦点时。使用 NSApplicationDelegate 的委托方法 applicationWillResignActive:applicationWillBecomeActive::

let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(self), userInfo: nil, repeats: true)
var resignDate: NSDate?
var stopwatch = 0

func update() {
    stopwatch += 1
}

func applicationWillResignActive(notification: NSNotification) {
    timer.invalidate()
    resignDate = NSDate() // save current time 
}

func applicationWillBecomeActive(notification: NSNotification) {
    if resignDate != nil {
        let timeSinceResign = NSDate().timeIntervalSinceDate(resignDate!))
        stopwatch += Int(timeSinceResign)
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(self), userInfo: nil, repeats: true)
        resignDate = nil
    }
}

applicationWillResignActive: 每次应用程序失去焦点时都会被调用。发生这种情况时,我将当前日期 (NSDate()) 保存在一个名为 resignDate 的变量中。然后,当应用程序被重新激活时(谁知道多久之后;没关系) applicationWillBecomeActive: 被调用。然后,我取另一个 NSDate 值,即当前时间,并找到当前时间和 resignDate 之间的时间量。将这段时间添加到我的时间值后,我可以重新验证 NSTimer 以便它继续进行。