使用CloudKit同步本地通知



我现在正在开发一个应用程序,该应用程序的核心数据数据库使用CloudKit同步。我想向应用程序添加通知,但不确定获取跨设备同步通知的最佳方式。它们将只是基于用户设置的截止日期的定时通知。通常,每当用户设置截止日期时,我只会简单地使用UNUserNotificationCenter来创建UNNotificationRequest,但我希望这些通知在设备之间同步,我不确定如何做到这一点。

我知道CloudKit可以用来发送推送通知,但它们似乎不应该用于像这样的简单时间触发器,是吗?

我现在最好的想法是监听NSPersistentStoreRemoteChange,并浏览每一个项目,检查它是否在设备上设置了通知,如果没有,则创建一个通知。不过,运行每次同步似乎有点繁重。

CloudKit通知被设计为在创建CKRecord时触发,而不是在用户设置的特定时间触发,这是正确的。

你所说的潜在解决方案正是我的做法。销毁所有以前的通知并添加新的通知只是向设备写入数据,所以它并不比本地数据库写入更密集。

以下是我如何在我的一个应用程序中做到这一点。这假设您有一个reminder对象数组,该数组具有用于显示通知信息的各种属性。这是适用于iOS的。macOS的代码略有不同,但如果你需要,我可以提供。

import UIKit
import UserNotifications
func setupNotifications(){
//Clear all the old notifications
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

//Build new notifications
for reminder in reminders{

let notification = UNMutableNotificationContent()

//Make sure we have a date property (reminder.date is a Date? optional)
guard let date = reminder.date else{ continue }

//Create a date components object from the reminder date
let reminderDateComponents = Calendar.current.dateComponents([.year, .month, .day], from: date)

//Set up a notification trigger in the future
let trigger = UNCalendarNotificationTrigger(dateMatching: reminderDateComponents, repeats: false)

notification.title = "Reminder Title"
notification.body = "(reminder.name) is due on (date)."
notification.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "Reminder.wav"))

//Register the notification request
let request = UNNotificationRequest(identifier: reminder.id, content: notification, trigger: trigger)

UNUserNotificationCenter.current().add(request) { error in
if let error = error{
print("Error scheduling notification: (error.localizedDescription)")
}
}
}
}

然后,你可以在应用程序中的某个地方调用setupNotifications(),无论你的数据在哪里更新(比如同步后(。

最新更新