0

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()
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Prakash Donga
  • 558
  • 5
  • 10
  • millisecond would have only 3 fraction digits – Leo Dabus Jan 15 '18 at 06:01
  • Btw why are you using `timeIntervalSince1970`? Just save the startTime `Date()` and then get the `startTime.timeIntervalSinceNow`. If you would like the resulting time interval to be positive just do `Date().timeIntervalSince(startTime)` – Leo Dabus Jan 15 '18 at 06:05
  • Btw There is no need to repeat a timer 100x per second. All you need is to update the UI 15/30 times per second. You don't need to display all values. – Leo Dabus Jan 15 '18 at 06:08

0 Answers0