如何获取当前用户创建的所有CloudKit记录?

时间:2016-02-08 13:44:47

标签: ios swift cloudkit ckquery ckrecord

说我有一个'物种'包含由许多用户创建的公共记录的记录类型。目前,我的查询检索了' 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)
        })
    }
}

如何才能获取当前用户创建的记录(如设备所有者)?

谢谢!

2 个答案:

答案 0 :(得分:7)

我也在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) 
  
    

然后正常使用查询。

  
     

快乐的取材!

答案 1 :(得分:1)

每个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)