Search code examples
iosapple-push-notificationscloudkit

CloudKit notifications


I might be missing something obvious here.

How would one create a CloudKit notification with detail about the CKRecord that you are being notified about? (i.e. not just a generic "New Item Created!" but a notification with the title of the record for instance, like, "Jill and Jessica's Birthday Party!")

Is the proper way to do this to create a new subscription with a new notification.alertBody for every new record change? That doesn't make any sense.

That leaves the option queryNotification.recordID to pull the data out of CloudKit (or my local store) and add it to the notification somehow? What's the method for adding or changing the values of an already notified notification? What am I missing?

Updated: Per Edwin's suggestion here's a code snippet, but it doesn't work.

let notification = CKNotificationInfo()
notification.alertBody = "Added: %@" as NSString
notification.alertLocalizationArgs = ["name"]

Solution

  • Just fill the .alertLocalizationArgs of the CKNotificationInfo object

    The documentation for the .alertLocalizationArgs says:

    Use of this property is optional. This property contains an array of NSString objects, each of which corresponds to a field of the record that triggered the push notification. Those names are used to retrieve the corresponding values from the record. The values are then used to replace any substitution variables in either the alertBody or alertLocalizationKey strings. The values themselves must be NSString, NSNumber, or NSDate objects. Do not specify keys with other values. String values that are greater than 100 characters in length may be truncated when added to the push notification.

    If you use %@ for your substitution variables, those variables are replaced by walking the array in order. If you use variables of the form %n$@, where n is an integer, n represents the index (starting at 1) of the item in the array to use. Thus, the first item in the array replaces the variable %1$@, the second item replaces the variable %2$@, and so on. You can use indexed substitution variables to change the order of items in the resulting string, which might be necessary when you localize your app’s messages.

    Here are 2 samples of how I use it:

                notificationInfo.alertBody = "%1$@ : %2$@"
                notificationInfo.alertLocalizationArgs = ["FromName", "Text"]
    

    And the 2nd sample:

                notificationInfo.alertLocalizationKey = "News: %1$@"
                notificationInfo.alertLocalizationArgs = ["Subject"]
    

    Where you have the "News: %1$@" as a key in the Localizable.strings file

    Update: It looks like you now require to use the .alertLocalizationKey. So the first sample does not work anymore.