当应用程序在后台时,我在我的应用程序中使用通知服务扩展来处理推送通知:
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)
}
}
}
但是,我注意到当应用程序位于我不想要的前台时也会调用它。
当应用程序处于前台时,我想从这个函数返回而不做任何事情,但是当我尝试“如果 UIApplication.shared.applicationState == .background”时,我收到上面包含的错误消息。
如何从此扩展检查应用程序状态?