[英]How do I fetch all CloudKit Records created by the current user?
Say I have a 'Species' Record Type that contains Public Records which were created by a number of Users. 假设我有一个'物种'记录类型,其中包含由许多用户创建的公共记录。 Currently, my query retrieves all records of 'Species':
目前,我的查询检索“物种”的所有记录:
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)
})
}
}
How can I only fetch records that were created by the current user (as in the owner of the device)? 如何只获取当前用户创建的记录(如设备所有者)?
Thank you! 谢谢!
I also posted on the Apple Developer Forums, and I was provided with an excellent solution : 我还在Apple开发者论坛上发帖,我获得了一个很好的解决方案 :
To fetch only a specific user records, you need to create a CKReference pointing to that user id (recordID), then use a predicate on that.
要仅获取特定用户记录,您需要创建指向该用户ID(recordID)的CKReference,然后在其上使用谓词。 It looks like this:
它看起来像这样:
First fetch the user record id
首先获取用户记录ID
yourContainer.fetchUserRecordIDWithCompletionHandler { (userID, error) -> Void in
if let userID = userID {
// here's your userID (recordID) to play with
}
}
Then construct the predicate:
然后构造谓词:
let reference = CKReference(recordID: userID, action: .None)
let predicate = NSPredicate(format: "creatorUserRecordID == %@", reference)
let query = CKQuery(recordType: "Species", predicate: predicate)
And then use the query as normal.
然后正常使用查询。
Happy fetching!
快乐的取材!
Each CKRecord
has a creatorUserRecordID
property; 每个
CKRecord
都有一个creatorUserRecordID
属性; therefore, you can try to get owner's userRecordID
first. 因此,您可以先尝试获取所有者的
userRecordID
。 Then, have it into NSPredicate
. 然后,让它进入
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.