【问题标题】:How to update CloudKit Subscriptions如何更新 CloudKit 订阅
【发布时间】:2016-03-28 18:11:27
【问题描述】:

我正在尝试使用 iOS、Swift 和 CloudKit 制作一个消息传递应用程序。我已经成功做到了,每当有人添加另一条消息时,我都会发送推送通知。但是,我希望推送通知的文本能够说明消息中的内容。这是我尝试过的:

发送通知的默认代码:

let subscription = CKSubscription(recordType: "Responses", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil), options: .FiresOnRecordCreation)
let notification = CKNotificationInfo()
notification.alertBody = "New Message Sent"
notification.soundName = UILocalNotificationDefaultSoundName

subscription.notificationInfo = notification

CKContainer.defaultContainer().publicCloudDatabase.saveSubscription(subscription) { (result, error) -> Void in
    if error != nil {
        print(error!.localizedDescription)
    }
}

这允许我为每条“新消息已发送”的消息发送通知。这是我为指定通知尝试过的:

//publicDB is the CKContainer.defaultContainer.publicDatabase
publicDB.fetchAllSubscriptionsWithCompletionHandler({ (subscriptions, error) in

    if error != nil {

        self.displayError(self.getStringFromError(error!))

    } else {

        for subscription in subscriptions! {

            subscription.notificationInfo?.alertBody = self.responseTextField.text

        }

    }

})

let record = CKRecord(recordType: "Responses")
record.setObject(currentUsername, forKey: "respondedBy")
record.setObject(responseTextField.text, forKey: "response")
publicDB.saveRecord(record) { (record, error) in
    //code for updating tables, etc.
    //Notification on other device sent
}

设置订阅的alertBody(我在上面尝试过的操作)不起作用。是否有任何其他解决方案可以更新订阅的 alertBody?谢谢!

【问题讨论】:

    标签: ios xcode swift push-notification cloudkit


    【解决方案1】:

    订阅无法更新。您必须先将其删除,然后再重新创建。

    但是,为什么要更改 alertBody?您最初可以将其设置为显示记录的响应字段。为此,您应该使用以下内容:

    notificationInfo?.alertLocalizationKey = "Response: %1$@"
    notificationInfo?.alertLocalizationArgs = ["response"]
    

    那么你的 Localization.Strings 文件中也需要这个。

    "Response: %1$@" = "Response: %1$@";
    

    在您的情况下,您希望在每次创建新消息时更改订阅。您将通知消息设置为与记录的字段之一相同。相反,您可以让 CloudKit 自动发送该字段。您只需创建一次订阅。在

    上方的 2 行代码中

    alertLocalizationKey 是在 Localization.Strings 文件中查找的键,alertLocalizationArgs 是将用于替换参数的 CloudKit 字段。

    有关本地化的更多信息,请参见 http://nshipster.com/nslocalizedstring/

    【讨论】:

    • 对不起,我不明白你的代码是如何工作的。那么在我将这些属性添加到我的通知信息之后,我应该怎么做呢?另外,Localization.Strings 是什么?感谢您的帮助
    • 我更新了答案...但是,如果您正在制作基于cloudkit的消息应用程序,那么我建议您应该看看:github.com/evermeer/EVCloudKitDao
    • 好的。当我有机会时,我会在今天下午尝试代码。我会让你知道情况如何。看起来很有希望!
    猜你喜欢
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多