I am using a notification service extension in my app to handle push notifications when the app is in the background:
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent {
if let userInfo = request.content.userInfo as? [String: AnyObject] {
if UIApplication.shared.applicationState == .background { // error 'shared' is unavailable in application extensions for iOS: Use view controller based solutions where appropriate
}
PushNotificationHelper.handleNotification(userInfo: userInfo, context: persistentContainer.viewContext)
contentHandler(bestAttemptContent)
} else {
contentHandler(bestAttemptContent)
}
}
}
However, I notice this is also being called when the app is in the foreground which I don't want.
I wanted to return from this function without doing anything when app is in foreground but when I try 'if UIApplication.shared.applicationState == .background' I get the error message included above.
How can I check the application state from this extension?