2016-03-15 59 views
1

我已經用秒錶製作了一個基本的應用程序。它運行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

回答

1

您不能在後臺使用NSTimer,並且您的應用無法運行很長時間。

當應用程序進入後臺時,應該停止計時器並記下當前時間。然後,當應用程序再次恢復時,您應重新啓動計時器,並計算應用程序在後臺運行多長時間以相應地更新顯示。

+0

因此,如果我創建一個變量來記錄當前時間並在用戶按下開始按鈕時運行此代碼。 on applicationwillenterbackground他們使計時器無效。然後在applicationwillenterforeground中減去變量中存儲的當前時間,然後將其寫入標籤並重新啓動nstimer。那個聽起來是對的嗎? –

+0

是的,這聽起來不錯。 – Michael