如何获取当前用户创建的所有 CloudKit 记录?
Posted
技术标签:
【中文标题】如何获取当前用户创建的所有 CloudKit 记录?【英文标题】:How do I fetch all CloudKit Records created by the current user? 【发布时间】:2016-02-08 13:44:47 【问题描述】:假设我有一个“物种”记录类型,其中包含由许多用户创建的公共记录。目前,我的查询检索“物种”的所有记录:
private func fetchSpecies()
// Fetch Public Database
let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase
// Initialize Query
let query = CKQuery(recordType: "Species", predicate: NSPredicate(format: "TRUEPREDICATE"))
// Configure Query
query.sortDescriptors = [NSSortDescriptor(key: "latinName", ascending: true)]
// Perform Query
publicDatabase.performQuery(query, inZoneWithID: nil) (records, error) -> Void in
dispatch_async(dispatch_get_main_queue(), () -> Void in
// Process Response on Main Thread
self.processResponseForQuery(records, error: error)
)
如何仅获取当前用户(如设备所有者)创建的记录?
谢谢!
【问题讨论】:
【参考方案1】:我还在 Apple 开发者论坛上发帖,并收到了 excellent solution:
要仅获取特定的用户记录,您需要创建一个指向该用户 ID (recordID) 的 CKReference,然后对其使用谓词。它看起来像这样:
首先获取用户记录id
yourContainer.fetchUserRecordIDWithCompletionHandler (userID, error) -> Void in
if let userID = userID
// here's your userID (recordID) to play with
然后构造谓词:
let reference = CKReference(recordID: userID, action: .None)
let predicate = NSPredicate(format: "creatorUserRecordID == %@", reference)
let query = CKQuery(recordType: "Species", predicate: predicate)
然后正常使用查询。
祝你愉快!
【讨论】:
【参考方案2】:每个CKRecord
都有一个creatorUserRecordID
属性;因此,您可以先尝试获取所有者的userRecordID
。然后,将其放入NSPredicate
。
let container: CKContainer = CKContainer.defaultContainer()
let completionHandler: (CKRecordID?, NSError?) -> Void = (userRecordID: CKRecordID?, error: NSError?) in
if let userRecordID = userRecordID
let predicate = NSPredicate(format: "creatorUserRecordID == %@", userRecordID)
let query = CKQuery(recordType: "Species", predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: "latinName", ascending: true)]
container.publicCloudDatabase.performQuery(query, inZoneWithID: nil) (records, error) -> Void in
//// Returns the user record ID associated with the current user.
container.fetchUserRecordIDWithCompletionHandler(completionHandler)
【讨论】:
以上是关于如何获取当前用户创建的所有 CloudKit 记录?的主要内容,如果未能解决你的问题,请参考以下文章