swift计算在后台运行的计时器的时间

时间:2016-01-07 20:54:01

标签: swift timer background

我想运行2个可互换的计时器,但即使应用程序在后台,我希望它们“运行”。

理想的行为是,用户启动计时器,进入后台并等待可互换计时器触发的通知......计时器可以多次交换。当用户将应用程序带回前台时......他希望看到当前计时器的准确时间。

在iOS模拟器中,计时器可以在后台运行,但在设备上却没有...

The interchangeable times 根据我附上的图片,我试图计算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)")
        }
    }
}
}

1 个答案:

答案 0 :(得分:2)

就个人而言,我认为A和B的合并持续时间是一个“周期”。然后,当应用程序重新启动时,我将进行模数计算以确定(a)自第一次启动计时器A以来已经过了多少个周期; (b)计算我们在当前周期内的位置。由此您可以轻松计算每个计时器下一次出现之前剩余的时间:

let elapsed = NSDate().timeIntervalSinceDate(startTime)

let totalDuration = durationOfTimerA + durationOfTimerB

let whereInCycle = elapsed % totalDuration
let cycleCount = Int(elapsed / totalDuration)

var timeUntilNextA: Double
var timeUntilNextB: Double

if whereInCycle < durationOfTimerA {
    timeUntilNextA = durationOfTimerA - whereInCycle
    timeUntilNextB = timeUntilNextA + durationOfTimerB
} else {
    timeUntilNextB = durationOfTimerA + durationOfTimerB - whereInCycle
    timeUntilNextA = timeUntilNextB + durationOfTimerA
}

if cycleCount < 1 {
    if whereInCycle < durationOfTimerA {
        print("timer A hasn't fired yet")
    } else {
        print("timer A has fired, but B hasn't")
    }
} else {
    if whereInCycle < durationOfTimerA {
        print("both timers A and B have fired \(cycleCount) times, and waiting for A to fire next")
    } else {
        print("timers A has fired \(cycleCount+1) times, but B has fired only \(cycleCount) times; we waiting for B to fire next")
    }
}

print("A will fire in \(timeUntilNextA) seconds; B will fire in \(timeUntilNextB)")