iosswiftnotificationscloudkitckrecord

How to show data from a CKRecord in alertBody of a Remote Notification?


In my app I have a public CloudKit database. I'm using it for remote subscriptions.

I've created a GlobalNotification Record in a CloudKit dashboard, created content field of a type String for this record and implemented the following method in my AppDelegate to make notifications work:

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let subscription = CKQuerySubscription(recordType: "GlobalNotification", predicate: NSPredicate(format: "TRUEPREDICATE"), options: .firesOnRecordCreation)

        let info = CKNotificationInfo()
        info.alertBody = "Some Text" // here i want to show content String data of a CKRecord which fired a notification
        info.shouldBadge = true
        info.soundName = "default"


        subscription.notificationInfo = info

        CKContainer.default().publicCloudDatabase.save(subscription, completionHandler: { subscription, error in
            if error == nil {
                // Subscription saved successfully
            } else {
                // An error occurred
            }
        })
    }

After that I create a new GlobalNotification record in a cloudKit dashboard, and add some "CloudKit content Text" in a content field for this record in a CloudKit dashboard. When notification fires on my device I see "Some text" text in it's alertBody, but I wan to see "CloudKit content Text".

I want this notification to show string taken from a GlobalNotification Record's content field. How should I change my code to achieve this?

I've read about desiredKeys and tried to add info.desiredKeys = ["content"] but it didn't helped. I've also googled, but have not found a solution.


Solution

  • You can't do that using just the alert body.

    There are three components you'll need to setup to make this work. You need to define a string with your message including replaceable parameters. Then you have to tell your notification to use that string. Finally you tell your notification which record field(s) to substitute into the string.

    First, you need to add a key/string pair to your localizable.strings file. In the string, you specify where you want to substitute parameters using %n$@ where "n" increments for each additional parameter.

    Second, in your notification, you need to set the .alertLocalizationKey to the keyname you specified in the strings file, above.

    Third, in your notification, set the .alertLocalizaionArgs property to an array of field names from your record.

    This Apple page gives examples of how to construct the string with the replaceable parameters: https://developer.apple.com/documentation/cloudkit/cknotificationinfo/1515182-alertlocalizationargs

    This question also shows some example code: (sample 1 doesn't work any more. Follow sample 2) CloudKit notifications