我已經用秒錶製作了一個基本的應用程序。它運行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
}
NSTimer是一個不用於後臺運行。 – tktsubota