秒表在后台睡眠模式下运行

问题描述:

我已经用秒表制作了一个基本的应用程序。它运行3个按钮 - 在导航栏上播放,暂停和重置,然后写入名为timerLabel的标签。秒表在后台睡眠模式下运行

问题是一旦应用程序关闭或iPhone进入睡眠模式秒表停止。我在其他问题上寻找答案,似乎唯一的解决办法是记录应用程序关闭的实际时间,并记录重新唤醒并比较差异的时间 - 然后将其写入标签

麻烦是我绝对不知道如何将其纳入我当前的代码。我甚至不知道如何得到时间。这是我的视图控制器的代码。

func updateTimer() { 

    time++ 

    updateTimeDisplay() 

} 

func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) { 
    let h = seconds/3600 
    let m = (seconds % 3600)/60 
    let s = (seconds % 60) 
    return (h, m, s) 
} 

func pauseTimer() { 
    timer.invalidate() 
} 

func startTimer() { 
    if !timer.valid { 
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTimer"), userInfo: nil, repeats: true)  } 
    else { 
    print("The Stopwatch has already started!") 
    } 
} 

func resetTimer() { 
    time = 0 
    timer.invalidate() 
    updateTimeDisplay() 

} 

func updateTimeDisplay() { 

    let (h, m, s) = secondsToHoursMinutesSeconds(time) 
    let timeToDisplay = String(format:"%02d:%02d:%02d", h, m, s) 
    timerLabel.text = timeToDisplay 

} 
+0

NSTimer是一个不用于后台运行。 – tktsubota

您不能在后台使用NSTimer,并且您的应用无法运行很长时间。

当应用程序进入后台时,应该停止计时器并记下当前时间。然后,当应用程序再次恢复时,您应重新启动计时器,并计算应用程序在后台运行多长时间以相应地更新显示。

+0

因此,如果我创建一个变量来记录当前时间并在用户按下开始按钮时运行此代码。 on applicationwillenterbackground他们使计时器无效。然后在applicationwillenterforeground中减去变量中存储的当前时间,然后将其写入标签并重新启动nstimer。那个听起来是对的吗? –

+0

是的,这听起来不错。 – Michael