用户收到推送通知后更新表视图中的数据

时间:2021-07-10 14:39:29

标签: swift push-notification realm

我有一个带有推送通知和 RealmDB 的应用程序。在通知日期进入 RealmDB 之后,用户自己选择通知日期。用户每次收到通知,下一次通知的日期都会发生变化,用户可以在 Table View 中看到该日期。问题是......用户收到通知后,他通过推送通知进入应用程序,因此 func 不起作用。如果用户通过打开它进入应用程序 - 一切正常。 在 cellForRowAt 中:

center.getDeliveredNotifications { (notifications) in
        for notification:UNNotification in notifications {
            print(notification.request.identifier)
            if (notification.request.identifier == timeId){
                
                let today = notification.date
                
                let realNextDate = Calendar.current.date(byAdding: .day, value: timeInterval!, to: today)
                
                let realm = try! Realm()
            
                try! realm.write {
                    for plants in realm.objects(MyPlant.self).filter("id == %@", timeId as Any) {
                        plants.nextDate = realNextDate
                        plants.prevDate = today
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为这背后的原因是您在 Realm 中配置了 AppDelegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    return true
}

这是当您通过点击 App icon 打开应用程序时执行的操作。如果您通过点击 push notification 打开应用程序,则不会执行上述 AppDelegate 方法。而是执行如下所示的方法,

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    // unused
}

因此,您还必须在此方法中进行一些配置,才能在点击通知时工作。

相关问题