Skip to content

Commit

Permalink
ensuring timer property is not deallocated and preventing crash on ge…
Browse files Browse the repository at this point in the history
…tter
  • Loading branch information
RishavG96 committed May 14, 2024
1 parent 220b0bc commit c496581
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,29 @@ import Foundation
class RepeatingTimer {

static let shared = RepeatingTimer()
var timeInterval: TimeInterval = 0
private var timeInterval: TimeInterval = 0
private var newTimer: DispatchSourceTimer?

private init() { }

init(timeInterval: TimeInterval) {
self.timeInterval = timeInterval
}

func setup(timeInterval: TimeInterval) {
self.timeInterval = timeInterval
setupTimer()
}

private func setupTimer() {
guard timeInterval > 0 else { return }
newTimer = DispatchSource.makeTimerSource()
newTimer?.schedule(deadline: .now() + timeInterval, repeating: timeInterval)
newTimer?.setEventHandler { [weak self] in
self?.eventHandler?()
}
}

private lazy var timer: DispatchSourceTimer = { [weak self] in
let t = DispatchSource.makeTimerSource()
guard let checkedSelf = self else { return t }
Expand All @@ -44,8 +59,13 @@ class RepeatingTimer {
private var state: Atomic<State> = Clickstream.timerCrashFixFlag ? Atomic(.notInitialized) : Atomic(.suspended)

deinit {
timer.setEventHandler {}
timer.cancel()
if Clickstream.timerCrashFixFlag {
newTimer?.setEventHandler {}
newTimer?.cancel()
} else {
timer.setEventHandler {}
timer.cancel()
}
/*
If the timer is suspended, calling cancel without resuming
triggers a crash. This is documented here https://forums.developer.apple.com/thread/15902
Expand All @@ -68,7 +88,11 @@ class RepeatingTimer {
state.mutate { state in
state = .resumed
}
timer.resume()
if Clickstream.timerCrashFixFlag {
newTimer?.resume()
} else {
timer.resume()
}
}

func suspend() {
Expand All @@ -78,6 +102,11 @@ class RepeatingTimer {
state.mutate { state in
state = .suspended
}
timer.suspend()

if Clickstream.timerCrashFixFlag {
newTimer?.suspend()
} else {
timer.suspend()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ final class DefaultKeepAliveServiceWithSafeTimer: KeepAliveService {
@discardableResult
private func makeTimer() -> RepeatingTimer? {
if Clickstream.timerCrashFixFlag {
let timerDuration = duration*reachability.connectionRetryCoefficient
RepeatingTimer.shared.timeInterval = timerDuration
self.timer = RepeatingTimer.shared
let timerDuration = duration*reachability.connectionRetryCoefficient
timer?.setup(timeInterval: timerDuration)
timer?.eventHandler = { [weak self] in
guard let checkedSelf = self else { return }
checkedSelf.performQueue.async {
Expand Down

0 comments on commit c496581

Please sign in to comment.