【问题标题】:swift calculate time for timers running in background快速计算在后台运行的计时器的时间
【发布时间】: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)")
        }
    }
}
}

【问题讨论】:

标签: swift timer background


【解决方案1】:

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

let elapsed = Date().timeIntervalSince(startTime)

let totalDuration = durationOfTimerA + durationOfTimerB

let whereInCycle = elapsed.remainder(dividingBy: 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)")

【讨论】:

  • 向@Rob 致敬!我不能感谢你!简单而优雅的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 2016-12-16
相关资源
最近更新 更多