首页 > 解决方案 > 使用swift杀死应用程序时如何存储ios推送通知

问题描述

我使用自己的服务器,使用FCM推送通知到ios设备,推送成功,我也使用Realm数据库系统帮我存储fcm推送通知,但是只有以下两种情况才能存储成功。案例1:应用程序运行时。

案例2:当你点击推送banner通知时,应用程序被杀死,或者在后台运行。

但这不是我的主要意图。我知道当应用程序被杀死时,我无法处理推送通知,所以我希望能够在用户打开应用程序时存储推送通知。

对不起,我的英语不好。如果有不清楚的地方,请告诉我。

领域类

class Order: Object {

    @objc dynamic var id = UUID().uuidString
    @objc dynamic var name = ""
    @objc dynamic var amount = ""
    @objc dynamic var createDate = Date()

    override static func primaryKey() -> String? {
        return "id"
    }

    let realm = try! Realm()
    let order: Order = Order()

AppDelegate.swift(当应用运行存储 fcm 消息时)

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {


        let userInfo = notification.request.content.userInfo //
        print("userInfo: \(userInfo)")

        guard
        let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
        let alert = aps["alert"] as? NSDictionary,
        let body = alert["body"] as? String,
        let title = alert["title"] as? String
        else {
            // handle any error here
            return
        }
        print("Title: \(title) \nBody:\(body)")

        order.name = title
        order.amount = body
        try! realm.write {
            realm.add(order)
        }
        completionHandler([.badge, .sound, .alert])
    }

单击以推送横幅通知 AppDelegate.swift(当应用程序终止或在后台单击以推送横幅通知)

   func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {  
        let userInfo = response.notification.request.content.userInfo

        print("userInfo: \(userInfo)")
        guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSDictionary,
            let body = alert["body"] as? String,
            let title = alert["title"] as? String
            else {
                // handle any error here
                return
        }
        print("Title: \(title) \nBody:\(body)")

        order.name = title
        order.amount = body
        try! realm.write {
            realm.add(order)
        }
        completionHandler()
    }

请有经验的人帮帮我,非常感谢。

标签: iosswiftfirebase-cloud-messagingapple-push-notifications

解决方案


当您的应用程序被终止时,您可以将通知存储到您的数据库中。

  1. “通知服务扩展”添加到您的应用程序。
  2. 在您的应用中启用后台获取/远程通知功能。
  3. 在您的应用程序中启用“应用程序组”并使用您的“通知服务扩展”启用相同的功能。

在此处输入图像描述

在此处输入图像描述

  1. 现在您可以使用“应用程序组”访问您的数据库,并且可以在收到通知后立即将通知插入到您的数据库中。

要使用“App Group”访问数据库,请使用,

var fileMgr : FileManager!
let databasePathURL = fileMgr!.containerURL(forSecurityApplicationGroupIdentifier: "<APP_GROUPS_ID>")

从上面的代码中,一旦您获得数据库的路径,您就可以对数据库执行插入操作。这将是您正在执行的正常插入操作。

在此文件和下图中突出显示的方法中插入用于保存数据的代码。

在此处输入图像描述

要访问您的文件到扩展,请按照下图进行操作。 在此处输入图像描述

如果您需要任何其他帮助,请告诉我。


推荐阅读