2017-11-02 16 views
0

시간 측정을위한 스톱워치 어플리케이션을 작성 중이며 시계가 특정 시간 간격 (예 : 20:00 - 06:00) 이상인지 확인해야하며이 경우 현재 경과 시간을 TimeInterval에 추가해야합니다 변수는 나중에 데이터베이스에 저장합니다. 내가 어떻게 이것을 달성 할 수 있는지에 대한 아이디어가 있습니까? 지금까지 나는 눈금 기능에서 그것을 검사하려고했지만 그 다음에 앱이 배경에있을 때를 추가하지 않는다.스톱워치 iOS Swift

import Foundation 
    import os.log 

/// The class protocol for a Stopwatch instance. 
protocol StopwatchDelegate: class { 
    func currentTimerUpdated(seconds: String, minutes: String, hours: String) 
    func timerHasStarted() 
    func timerHasStopped() 
    func timerWasReset() 
} 

/// A container for a stopwatch. 
class Stopwatch{ 

    //var currentTimerSession = [TimerSession] = [] 

    // ***************************************************************** 
    // MARK: - Stopwatch Properties 
    // ***************************************************************** 

    /// The middleman for communicating with the view controller. 
    weak var delegate: StopwatchDelegate? 

    /// The actual Timer for this stopwatch. 
    private(set) var timer: Timer? 

    /// The time at which the timer was started. 
    private(set) var timerStartTime: TimeInterval = 0 

    /// The Timer-time at which the last user *pause* occurred. 
    private(set) var timerSavedTime: TimeInterval = 0 

    private(set) var timerSession = false 

    // ***************************************************************** 
    // MARK: - Stopwatch Class Methods 
    // ***************************************************************** 
    /// Create a new Stopwatch by locating the middleman and starting the timer. 
    /// 
    /// - Parameter delegate: the middleman to communicate to the view controller. 
    /// - Returns: An instance to a ticking `Stopwatch`. 
    /// 
    init(delegate: StopwatchDelegate) { 
     os_log("Initilzing timer.", log: OSLog.default, type: .debug) 
     self.delegate = delegate 
    } 

    // ***************************************************************** 
    // MARK: - Stopwatch Timer Methods 
    // ***************************************************************** ***************************************************************** 

    /// Start the stopwatch's timer. 
    func startTimer() { 
     timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, 
            selector: #selector(timerHasTicked(timer:)), 
            userInfo: nil, repeats: true) 
     RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes) 

     /// Record the time at which we started this timer. 
     //checkForOngoingTimer() 
     timerStartTime = Date.timeIntervalSinceReferenceDate 

     timerOriginalStartTime = Date() 
     timerSession = true 


     delegate?.timerHasStarted() 
    } 

    /// Pause the Timer 
    func stopTimer() { 
     /// Save the Time delta of the current Timer. 
     let currentTime = Date.timeIntervalSinceReferenceDate 
     timerSavedTime += currentTime - timerStartTime 
     timer?.invalidate() 
     delegate?.timerHasStopped() 
    } 

    /// Reset the Timer and all of the laps. 
    func resetTimer() { 
     timerSavedTime = 0 
     timerStartTime = 0 
     timerSession = false 

     timer?.invalidate() 
     delegate?.timerWasReset() 
    } 

    /// Compute the new time values time values: 
    /// 
    /// - `minutes`: starts at 0 and increments to 59 
    /// - `seconds`: starts at 0 and increments to 59 
    /// - `hours`: starts at 0 and increments to 59 
    /// 
    /// - Parameter timer: The instance of the currently *running* Timer. 
    /// 
    @objc private func timerHasTicked(timer: Timer) { 

     /// Find the time delta between start time and now. 
     let currentTime = Date.timeIntervalSinceReferenceDate 
     let timerElapsedTime: TimeInterval = (currentTime - timerStartTime) + timerSavedTime 

     /// Convert elapsed time to minutes, seconds, and hours. 
     let minutes = Int(timerElapsedTime)/60 % 60 
     let seconds = Int(timerElapsedTime) % 60 
     let hours = Int(timerElapsedTime/3600) 

     let formatter = DateFormatter() 
     formatter.timeZone = TimeZone.current 
     formatter.dateFormat = "yyyy-MM-dd HH:mm" 
     timerOriginalStartTime = formatter.string(from: timerOriginalStartTime) 

     /// Let the delegate know the Time has been updated. 
     delegate?.currentTimerUpdated(seconds: String(format: "%02u", seconds), 
             minutes: String(format: "%02u", minutes), 
             hours: String(format: "%02u", hours)) 
    } 
    } 
+0

App Capabities에서 백그라운드 모드를 활성화 한 후에 사용해 보셨습니까? –

답변

2

귀하의 타이머가 백그라운드에서 해고, 그렇습니다 갈 수있는 가장 좋은 방법은 스톱워치를 시작할 때 시작 시간을 저장하는 것입니다되지 않습니다, 다음 앱이 백그라운드로 이동하고 다시 올 때, 시작 시간부터 현재 오프셋을 계산할 수 있습니다.

타이머 일시 중지를 지원하려면 일시 중지의 시작 및 중지 시간을 추적하고 총 시간에서 해당 시간을 뺍니다.

+0

내가 그렇게 생각하고 있었는데, 문제는 사용자가 타이머를 일시 중지 할 수 있기를 원했기 때문에 모든 시작 시간과 종료 시간을 저장해야한다는 것이 었습니다. 모든 시작과 끝 시간을 어떻게 처리 할 수 ​​있을지에 대한 아이디어가 있습니까? –

+0

일시 중지를 지원하려면 사용자가 일시 중지를 누르는 시간을 기록하십시오. 그런 다음 사용자가 타이머를 다시 시작하면'interval = (currentTime - pauseTime)'을 계산하여 원래 시작 시간에 추가하고이를 시작 시간으로 사용하십시오. 이 방법을 사용하면'startTime'과'pauseTime'의 2 회 추적 만하면됩니다. – vacawama