Nikhil Sridhar
Nikhil Sridhar

Reputation: 1740

Fetching Multiple Records by Record Name

I have an array of record names (or strings) . I want to fetch any record in the public database which has any of these record names. How might I do this?

Upvotes: 0

Views: 1527

Answers (2)

Andy
Andy

Reputation: 4531

Check out CKFetchRecordsOperation(recordIDs: [CKRecord.ID])

you didn't include a code example, but if you have the recordIDs as an array of Strings then:

let ids: [String] = [...] // your array of the record names as Strings 
let recordIDs = ids.map { CKRecord.ID(recordName: $0) }
let operation = CKFetchRecordsOperation(recordIDs: recordIDs)
operation.fetchRecordsCompletionBlock = { (ckRecords, error) in
  ... // do stuff with your records
}
CKContainer.default().publicCloudDatabase.add(operation)

Upvotes: 3

Adolfo
Adolfo

Reputation: 1862

You should apply something like this...

let filter: [String] = [ "String1", "String2", "String3" ]

let predicate: NSPredicate = NSPredicate(format: "%k IN %@", "record_name", filter)
let query: CKQuery = CKQuery(recordType: "RecordType", predicate: predicate)

CKContainer.default.publicCloudDatabase.perform(query, inZoneWith: nil, completionHandler: { @escaping ([CKRecord]?, Error?) -> Void in 
    // Do what you want with your filtered CKRecords ;)
})

The NSPredicate uses the aggregated operator IN in order to filter by the contents of an array. More info at Predicate Programming Guide

Upvotes: 5

Related Questions