Skip to content

Commit

Permalink
🐛 Update PushMonitor to track new status on main thread
Browse files Browse the repository at this point in the history
Tracking an event at startup from a background thread can cause data races
  • Loading branch information
mmaatttt committed Dec 11, 2024
1 parent 65c5ede commit 414b7ae
Showing 1 changed file with 16 additions and 12 deletions.
28 changes: 16 additions & 12 deletions Sources/AppcuesKit/Push/PushMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,17 +87,9 @@ internal class PushMonitor: PushMonitoring {
}

func refreshPushStatus(completion: ((UNAuthorizationStatus) -> Void)? = nil) {
// Skip call to UNUserNotificationCenter.current() in tests to avoid crashing in package tests
#if DEBUG
guard ProcessInfo.processInfo.environment["XCTestBundlePath"] == nil else {
completion?(pushAuthorizationStatus)
return
}
#endif

UNUserNotificationCenter.current().getNotificationSettings { [weak self] settings in
let shouldPublish = self?.appcues?.sessionID != nil && self?.pushAuthorizationStatus != settings.authorizationStatus
self?.pushAuthorizationStatus = settings.authorizationStatus
let handler: ((UNAuthorizationStatus) -> Void) = { [weak self] newStatus in
let shouldPublish = self?.appcues?.sessionID != nil && self?.pushAuthorizationStatus != newStatus
self?.pushAuthorizationStatus = newStatus

if shouldPublish {
self?.analyticsPublisher.publish(TrackingUpdate(
Expand All @@ -106,7 +98,19 @@ internal class PushMonitor: PushMonitoring {
))
}

completion?(settings.authorizationStatus)
completion?(newStatus)
}

// Skip call to UNUserNotificationCenter.current() in tests to avoid crashing in package tests
#if DEBUG
guard ProcessInfo.processInfo.environment["XCTestBundlePath"] == nil else {
handler(pushAuthorizationStatus)
return
}
#endif

UNUserNotificationCenter.current().getNotificationSettings { settings in
DispatchQueue.main.async { handler(settings.authorizationStatus) }
}
}

Expand Down

0 comments on commit 414b7ae

Please sign in to comment.