0

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?

alionthego
  • 8,508
  • 9
  • 52
  • 125
  • 1
    The extension runs in a different context. You could share a user defaults set between your app and your extension and set/clear a boolean when your app enters the foreground/background – Paulw11 Nov 09 '21 at 09:54
  • I'll try that. thanks very much – alionthego Nov 09 '21 at 09:55

0 Answers0