首页 > 解决方案 > 应用程序终止或终止时如何在 coredata 中存储推送通知?

问题描述

当应用程序终止或终止时,我试图将推送通知(FCM)存储在coredata中。它不工作。但是当应用程序处于后台状态时存储完美。当我单击通知时,它也完美存储。但我不能存储在coredata被杀状态。

我正在使用FCM通知

  1. 当应用程序被杀死状态时,iOS可能的通知存储核心数据吗?
  2. 应用程序被杀死时存储核心数据的任何解决方案。

标签: iosswiftcore-datapush-notificationfirebase-cloud-messaging

解决方案


您可以使用UNNotificationServiceExtension. 这旨在用作拦截器,以在呈现给用户之前修改传入通知的内容。但是,您可以使用此拦截器将通知保存到 CoreData。请务必在通知数据有效负载上设置mutable-content为。1只有这些会被拦截。

FCM 支持这一点mutable-content,我在我的一个项目中做了一些非常相似的事情,以确认我的后端用户收到通知并且它完美地工作。

import UserNotifications

class NotificationService: UNNotificationServiceExtension {
    
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
    
    override func didReceive(_ request: UNNotificationRequest,
                             withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = request.content.mutableCopy()
        
        // TODO
        // Save the notification to core data
        
        contentHandler(request.content)
    }
    
    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler,
           let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}

推荐阅读