We are developing a game to find a mismatch, the one who finds in the lowest time wins the game. Currently, we have used DispatchSourceTimer
to perform the tracking of timing in the unit of seconds SS.XXXX with 4 decimal point in consideration, so you can consider this as a stopwatch with millisecond timer.
Right now we are facing a challenge that timer in devices like iPhone 5 with iOS 10 or above timer runs slower compared to iPhone 7/X, also the accuracy of the time elapsed is not accurate, I tried to compare time with the app available on App Store called WatchStop and found the issue in our code/app. I want to achieve the same functionality described as Jiffies in the WatchStop app.
Below is some of the snippet of the code.
private final var gamePlayingTime: TimeInterval = 0.0
private final var gamePlayingTimer: DispatchSourceTimer?
/*Start timer funtion*/
final func startGamePlayTimer() {
gamePlayingTimer?.cancel()
let queue = DispatchQueue(label: "com.findmismatch.app.precised_timer", qos: .userInteractive)
gamePlayingTimer = DispatchSource.makeTimerSource(flags: .strict, queue: queue)
gamePlayingTimer?.schedule(deadline: .now(),
repeating: .microseconds(100),
leeway: .nanoseconds(0))
gamePlayingTimer?.setEventHandler { [weak self] in
self?.didTriggeredTimerEvent()
}
gamePlayingTimer?.resume()
}
/*Trigger function to update Label - UI*/
final func didTriggeredTimerEvent() {
guard !ignoreTimerTriggers else { return }
let startTime = abs(contest.startTime.timeIntervalSince1970)
let currentTime = Date().timeIntervalSince1970
gamePlayingTime = (currentTime - startTime) + penaltyInSeconds
DispatchQueue.main.async { [weak self] in
self?.updateTimeLabel()
}
if gamePlayingTime >= cutOffInterval {
ignoreTimerTriggers = true
gamePlayingTimer?.cancel()
DispatchQueue.main.async { [weak self] in
self?.didTimeoutGamePlay()
}
}
}