ios - 如何通过 NotificationService 扩展检查我的 SwiftUI 应用程序是否在后台?
问题描述
当应用程序在后台时,我在我的应用程序中使用通知服务扩展来处理推送通知:
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”时,我收到上面包含的错误消息。
如何从此扩展检查应用程序状态?
解决方案
推荐阅读
- android - Firebase 子节点公开
- visual-studio-code - 配置多个命令以在 VS Code 任务中并行运行(编译和自动添加 Sass 前缀)
- python - 如何调整刻度数?
- python - 为 Excel 中的键分配多个值(Python 字典)
- monetdb - 是否可以在 Windows 上运行 MonetDB 集群?
- javascript - 如何获取和移除querySelectorAll的parentNode
- javascript - 如何设置控制台数据记录的间隔
- python-3.x - 在等待文本字段变为可使用 selenium 和 python 3.8 编辑时接收 NoSuchElementException
- python - ImportError:libpython3.7m.so.1.0:无法打开共享对象文件:没有这样的文件或目录
- java - 如何将格式日期“MMddhhmmss”转换为“yyyy-MM-dd HH:mm:ss”?