시간 측정을위한 스톱워치 어플리케이션을 작성 중이며 시계가 특정 시간 간격 (예 : 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))
}
}
App Capabities에서 백그라운드 모드를 활성화 한 후에 사용해 보셨습니까? –