Skip to content

Commit 22878e4

Browse files
authored
Dispatch timer updates to main queue (#6)
1 parent 85fffc7 commit 22878e4

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

Sources/SegmentAmplitude/AmplitudeSession.swift

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -148,20 +148,26 @@ extension AmplitudeSession {
148148
}
149149

150150
func startTimer() {
151-
sessionTimer?.invalidate()
152-
sessionTimer = Timer(timeInterval: fireTime, target: self,
153-
selector: #selector(handleTimerFire(_:)),
154-
userInfo: nil, repeats: true)
155-
sessionTimer?.tolerance = 0.3
156-
if let sessionTimer = sessionTimer {
157-
// Use the RunLoop current to avoid retaining self
158-
RunLoop.current.add(sessionTimer, forMode: .common)
151+
// Starting and stopping the timer has to be done from the same thread; always dispatch to main queue
152+
DispatchQueue.main.async {
153+
self.sessionTimer?.invalidate()
154+
self.sessionTimer = Timer(timeInterval: self.fireTime, target: self,
155+
selector: #selector(self.handleTimerFire(_:)),
156+
userInfo: nil, repeats: true)
157+
self.sessionTimer?.tolerance = 0.3
158+
if let sessionTimer = self.sessionTimer {
159+
// Use the RunLoop current to avoid retaining self
160+
RunLoop.current.add(sessionTimer, forMode: .common)
161+
}
159162
}
160163
}
161164

162165
func stopTimer() {
163-
sessionTimer?.invalidate()
164-
sessionID = -1
166+
// Starting and stopping the timer has to be done from the same thread; always dispatch to main queue
167+
DispatchQueue.main.async {
168+
self.sessionTimer?.invalidate()
169+
self.sessionID = -1
170+
}
165171
}
166172
}
167173

0 commit comments

Comments
 (0)