Search code examples
iosswiftcloudkit

iOS Swift Cloudkit performQuery function


I'm trying to build a loop here that will let me freely add new buckets on the Cloudkit dashboard without having to update the app. One of the attributes for my recordType is Bucket, and it is type Int(64). I have my items categorized by buckets, starting with 1 increasing by 1. The goal of the loop is to find which bucket doesn't have a CKRecord associated, and return the number of the last bucket that had a CKRecord for use later in the app.

My problem is that as you can see I included println() statements to check what was being processed and what wasn't, and while it printed "first", it never printed "here" or "there", indicating it never ran the performQuery function.

Thanks in advance for your help!

for bucket in 1...1000 {

        let bucketPredicate = NSPredicate(format: "Bucket = \(bucket)")
        let bucketQuery = CKQuery(recordType: "CardRecordType", predicate: bucketPredicate)

        // Make this error handling perfect
        println("first")
        publicDatabase.performQuery(bucketQuery, inZoneWithID: nil) {
            results, error in
            if error != nil {
                println("here")
                if error.code == 11 {
                    println(error.localizedDescription)
                    var bucketNumber = (bucket - 1)
                }
                else {
                    println(error.localizedDescription)
                }
            }
            else {
                println("there")
                println(results)
            }
        }
    }

Solution

  • You could accomplish the same by doing only one query. Just query your CardRecordType with a true predicate and sort your query on the field Bucket descending. The first record will be the one whith the highest Bucket number.

    query.sortDescriptors = [NSSortDescriptor(key: "Bucket", ascending: false)]
    

    You could even limit the result by using a CKQueryOperation and setting the .resultsLimit to 1