diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d8182c455e..23a7b999cd0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - Stop sending empty thread names (#3361) - Work around edge case with a thread info kernel call sometimes returning invalid data, leading to a crash (#3364) +- Reading applicationState in the background (#3372) ## 8.14.2 diff --git a/Sources/Sentry/SentryUIApplication.m b/Sources/Sentry/SentryUIApplication.m index d87b5333082..53f1f455246 100644 --- a/Sources/Sentry/SentryUIApplication.m +++ b/Sources/Sentry/SentryUIApplication.m @@ -4,7 +4,34 @@ # import -@implementation SentryUIApplication +@implementation SentryUIApplication { + UIApplicationState appState; +} + +- (instancetype)init +{ + if (self = [super init]) { + [NSNotificationCenter.defaultCenter addObserver:self + selector:@selector(didEnterBackground) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; + + [NSNotificationCenter.defaultCenter addObserver:self + selector:@selector(didBecomeActive) + name:UIApplicationDidBecomeActiveNotification + object:nil]; + // We store the application state when the app is initialized + // and we keep track of its changes by the notifications + // this way we avoid calling sharedApplication in a background thread + appState = self.sharedApplication.applicationState; + } + return self; +} + +- (void)dealloc +{ + [NSNotificationCenter.defaultCenter removeObserver:self]; +} - (UIApplication *)sharedApplication { @@ -58,7 +85,17 @@ - (UIApplication *)sharedApplication - (UIApplicationState)applicationState { - return self.sharedApplication.applicationState; + return appState; +} + +- (void)didEnterBackground +{ + appState = UIApplicationStateBackground; +} + +- (void)didBecomeActive +{ + appState = UIApplicationStateActive; } @end