我无法找到正确的方法来检查CKRecord订阅是否已经存在,如果它没有订阅它以获得推送通知。
我已经实现了订阅本身并且它正在响应,但每次我进入正确的View Controller时,我总是尝试再次订阅,如果订阅已经,则服务器会回复错误存在 - 我的问题是:有没有办法先检查订阅是否存在而不是尝试创建它并等待服务器响应?
以下是我订阅唱片的方式:
// Create the predicate
let predicate = NSPredicate(format: "recordId = %@", RECORD_ID)
// Create a subscription specifying the record type, predicate and notification options
let subscription = CKQuerySubscription(recordType: "Tabs", predicate: predicate, options: [.firesOnRecordUpdate, .firesOnRecordCreation])
// Create a CloudKit notification object
let notificationInfo = CKNotificationInfo()
notificationInfo.alertLocalizationKey = "Updates have been made"
notificationInfo.shouldBadge = true
// Set the subscriptor's notification object to the new CloudKit notification object
subscription.notificationInfo = notificationInfo
// Save the subscription to the database
let publicDatabase = CKContainer.default().publicCloudDatabase
publicDatabase.save(subscription) { (subs, err) in
if let err = err {
print("Failed to save subscription:", err)
return
}
}
由于
答案 0 :(得分:3)
您可以使用fetchAllSubscriptionsWithCompletionHandler
查询所有现有的subs,然后可以检查完成处理程序中返回的每个子上的subscriptionID
属性。 objective-c版本看起来像:
[publicDatabase fetchAllSubscriptionsWithCompletionHandler:^(NSArray<CKSubscription *> * _Nullable subscriptions, NSError * _Nullable error)
{
NSMutableArray *subIDs = [NSMutableArray new];
for (CKSubscription *sub in subscriptions)
{
if ([sub.subscriptionID isEqualToString:@"whatever"];
{
//do some stuff
}
}
}];
但是,您提到重新进入视图控制器并重新运行此检查。并非此检查每次都向服务器发出请求,因此将计入您的交易和转移配额。我建议您在应用启动时运行此检查一次,然后在类变量中保存每个子状态,这样您就不必通过不必要的调用反复重新查询服务器。