Search code examples
iosswiftcloudkit

Search and return single field of cloudkit records


I have cloudKit records in the format

KeyWords : String
Content : Asset

Where the assets are approx 100k.

I'm using a SearchDisplayController to query the public database but it's returning the entire record. Every tutorial I can find does this too.

Is there a way to only return the KeyWords field eg by using predicates in a certain way?


Solution

  • OK Got something working. This may well be hacky but I put it up for info for anyone else in the same situation...

    let predicate = NSPredicate(value: true) // returns all - replace with whatever condition you want
    let query = CKQuery(recordType: "Library", predicate: predicate) // create a query using the predicate
    var operation = CKQueryOperation(query: query) // create an operation using the query
    operation.desiredKeys = ["KeyWords"] // Array of whatever 'columns' you want to return
    // operation.resultsLimit = 15 // optional limit on records
    
    // Define a closure for what to do for each returned record
    operation.recordFetchedBlock = { [weak self] (record:CKRecord!) in
    
        // Do whatever you want with each returned record  
        println(record.objectForKey("KeyWords"))
    
    }
    
    // Define a closure for when the operation is complete
    operation.queryCompletionBlock = { [weak self] (cursor:CKQueryCursor!, error:NSError!) in
    
            if cursor != nil {
                // returns the point where the operation left off if you want t retrieve the rest of the records
            }
    
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
    
                // Do what you want when process complete
                self!.tableView.reloadData()
                if error != nil {
                    println("there was an error")
                }
            })
        }
    
    self.publicDatabase!.addOperation(operation) // Perform the operation on given database