如何在 CloudKit 中删除订阅

How to delete a subscription in CloudKit

我想删除一个特定的订阅,但我不知道如何获取订阅 ID。删除订阅有几个选项,所有这些都需要提前知道订阅 ID:

  1. delete(withSubscriptionID:completionHandler:)

示例:

let database = CKContainer.default().publicCloudDatabase
database.delete(withSubscriptionID: subscription.subscriptionID) { (result, error) in
   // completed 
}
  1. fetchAllSubscriptions(completionHandler:)

示例:

let database = CKContainer.default().publicCloudDatabase
database.fetchAllSubscriptions { subscriptions, error in
    if error == nil {
        if let subscriptions = subscriptions {
            // find the subscription ID of my choice and use the method from #1 to delete
        }
    } else {
        print(error!.localizedDescription)
    }
}
  1. CKModifySubscriptionsOperation

示例:

let operation = CKModifySubscriptionsOperation(subscriptionsToSave: [], subscriptionIDsToDelete: [subscriptionID])
operation.modifySubscriptionsCompletionBlock =  {
    (modifiedSubscriptions: [CKSubscription]?, deletedSubscriptionIDs: [String]?, error: Error?) -> Void in

    if error != nil {
        print(error!.localizedDescription)
    } else {
        print("Success!")
    }
}
operation.qualityOfService = .utility
privateDatabase.add(operation)

保存和删除Core Data记录,可以使用recordName获取CKRecord ID,在Core Data中更容易保存:

let recordID = CKRecord.ID(recordName: recordName)

订阅是否有类似的东西,或者我是否必须在创建订阅 ID 时保存订阅 ID?看起来 CKQuerySubscription 甚至没有 recordName:

[<CKQuerySubscription: 0x283a3be40; ; Query Subscription: recordType=Progress, predicate=userId == "_sdfd1cedfea6965asdfdsc58e3d", subscriptionOptions=1, subscriptionID=SDF23BB6B-2C15-4F4D-BE7F-DF234GS, zoneID=(null)>
{
    alertBody -> New Post!
    alertLocalizationKey -> "(null)
    alertLocalizationArgs -> []
    title -> My App
    titleLocalizationKey -> "(null)
    titleLocalizationArgs -> []
    subtitle -> (null)
    subtitleLocalizationKey -> "(null)
    subtitleLocalizationArgs -> []
    alertActionLocalizationKey -> (null)
    alertLaunchImage -> (null)
    soundName -> default
    desiredKeys -> []
    shouldBadge -> NO
    shouldSendContentAvailable -> NO
    shouldSendMutableContent -> NO
    category -> (null)
    collapseIDKey -> (null)

}])

您如何开始创建 CKQuerySubscription?您在创建它时为其指定一个 ID,这就是您知道 subscriptionID 是什么的方式:

let subscriptionWorkspace = CKQuerySubscription(
  recordType: "YourRecordType",
  predicate: ...,
  subscriptionID: "Your-ID-Goes-Here",
  options: [...]
)

如果您要创建对个人 CKRecord 的订阅,那么您可以创建一个 subscriptionID,例如:

"YourRecordType|\(recordName)"

不过,通常有比一次订阅一条记录更好的方法来订阅具有 predicate 条件的整个记录​​类型。

如果您需要进一步的帮助,请添加有关创建 CKQuerySubscription 的更多详细信息。