【问题标题】:How to store pushnotification in coredata when app is terminated or killed?应用程序终止或终止时如何将推送通知存储在核心数据中?
【发布时间】:2021-09-28 13:47:11
【问题描述】:

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

我正在使用 FCM 通知

  1. 当应用被终止状态时,iOS 中是否有可能的通知存储 coredata
  2. 在应用被终止时存储 coredata 的任何解决方案。

【问题讨论】:

  • 当应用程序被杀死时,它无法接收推送通知。无论如何都不能保证推送通知。当您的应用启动时,它应该从服务器拉取任何更新
  • 感谢您的回复。是的,它是检索和存储的一种方式。我们已经在和我的团队讨论了。将通知存储在核心数据中的任何其他可能方式?非常感谢您的回复

标签: ios swift core-data push-notification firebase-cloud-messaging


【解决方案1】:

您可以使用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)
        }
    }
}

【讨论】:

  • 谢谢兄弟的回复。谢谢,我会检查并告诉你。我有一个疑问:如果后端添加可变内容,我们可以通过您的扩展将数据存储在本地。你来自泰米尔纳德邦吗?
  • 嗨,我正在尝试这个。无法存储在 coredata 中。你能解释一下这个功能吗?
【解决方案2】:

您可以更改有效负载的工作方式。我这边换了有效载荷,工作正常。

Background modes。检查您的后台模式。

更改您的有效负载:

  {
     "to": "Device GCM Id",
     "content_available": true,
     "mutable_content": true,
     "notification":
      {
        "body":"Your Notification message",
        "sound": "default",
        "title":"Your App tittle"
     }
  }

应用代理:

   func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
 {
       // Save pushnotification data to core data
 }

当你的应用被杀时,这个方法应该保存在 coredata 中。我这边 100% 工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2016-05-05
    • 1970-01-01
    • 2017-12-01
    相关资源
    最近更新 更多