【发布时间】:2016-04-12 10:07:58
【问题描述】:
我想运行 2 个可互换的计时器,但我希望它们“运行”,即使应用程序在后台。
理想的行为是,用户启动计时器,进入后台并等待可互换计时器触发的通知......计时器可以互换很多次。当用户将应用程序带回前台时......他想查看当前计时器的准确时间。
在 iOS 模拟器中,计时器确实在后台工作,但在设备上却不行......
根据我附上的图片,我正在尝试计算 X 当前计时器应该到期的时间,并根据结束时间获取当前时间。代码如下:
func appDidBecomeActive(){
// TODO: calculate time spend in background
isInBackground = false
if let startTime = startTime{
let now = NSDate()
var timeFromBegining = now.timeIntervalSinceDate(startTime)
while timeFromBegining > userDefaultsHelper.timerAseconds(){
timeFromBegining -= userDefaultsHelper.timerAseconds()
timerType = .tiemrTypeB
let stopTimeSeconds = userDefaultsHelper.timerBseconds() - timeFromBegining
stopTime = NSDate().dateByAddingTimeInterval(stopTimeSeconds)
print("Time from Begining: \(timeFromBegining)")
if timeFromBegining > userDefaultsHelper.timerBseconds(){
timeFromBegining -= userDefaultsHelper.timerBseconds()
timerType = .timerTypeA
// TODO: do something with the remaining time ...
let stopTimeSeconds = userDefaultsHelper.timerAseconds() - timeFromBegining
stopTime = NSDate().dateByAddingTimeInterval(stopTimeSeconds)
print("Time from Begining: \(timeFromBegining)")
}
}
}
}
【问题讨论】:
-
这看起来太简单了。将您的问题简化为最基本的必需品。
-
@GrantPark - 仅供参考,这是stackoverflow.com/questions/34496389/… 的后续问题。
标签: swift timer background