我正在处理其中一种代码,其中我使用CloudKit将数据发布到iCloud并从那里获取数据。我能够获取数据并将其显示在表格视图中。但是我正在尝试设置通知,以便从一台设备将数据插入到icloud时,另一台设备应以默认声音接收通知。
我添加了一些功能,如AppDelegate.swift文件,以及在我的viewcontroller文件中,如下面的代码所示。
AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {authorized, error in
if authorized {
DispatchQueue.main.async (execute: {
application.registerForRemoteNotifications()
})
}
})
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
application.applicationIconBadgeNumber = 0
}
func applicationDidBecomeActive(_ application: UIApplication) {
application.applicationIconBadgeNumber = 0
}
AppDelegate外部类
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound, .badge])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
completionHandler()
}
}
在ViewController.swift文件中
func setupCloudSubscription() {
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: "subscribed") == false {
let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
let subscription = CKQuerySubscription(recordType: "RecordName", predicate: predicate, options: CKQuerySubscription.Options.firesOnRecordCreation)
let notificationInfo = CKSubscription.NotificationInfo()
notificationInfo.alertLocalizationKey = "New Added"
notificationInfo.shouldBadge = true
subscription.notificationInfo = notificationInfo
let publicData = CKContainer.default().publicCloudDatabase
publicData.save(subscription, completionHandler: {subscription, error in
if error != nil {
print(error?.localizedDescription)
} else {
userDefaults.set(true, forKey: "subscribed")
userDefaults.synchronize()
}
})
}
}
当前,发送通知时,徽章编号显示5或7或4等。如果要发送一个通知,我希望徽章编号显示1,如果发送两个通知,则我希望徽章编号显示2。此外,每次发送的通知我都听不到声音。