Search code examples
swiftcloudkitckquery

performQuery, cannot set inZoneWithID to nil


Hi I am trying to make a small function that should send me back the record that corresponds to the user by entering his/her name. I created a swift file:

import Foundation
import CloudKit
import UIKit


func getGetMainUser(name : String) -> CKRecord {
var myRecord : CKRecord!
let container = CKContainer.defaultContainer()
let publicDB = container.publicCloudDatabase
let predicate = NSPredicate(format: "nickName == name")
let query = CKQuery(recordType: "usersAtributes", predicate: predicate)

publicDB.performQuery(query, inZoneWithID: nil) {
    record, error in {
        if error != nil {
            println(error.localizedDescription)
        } else {
            if record.count == 1 {
                myRecord = record[0] as CKRecord
            }
        }
    }
}
return myRecord
}

What I don't understand is that I cannot compile this code because of the nil value of inZoneWithID of the performQuery. This syntax might be incorrect though it works in other parts of my code. This is the error I get :

Cannot convert the expression's type '(CKQuery!, inZoneWithID: NilLiteralConvertible, ((ST5,(ST5,ST6) -> (ST5, ST6) -> ST4) -> (ST5,(ST5,ST6)-> ST4) -> ST4,((ST5,ST6) -> (ST5,ST6)...

Solution

  • Your problem is not the zoneID. The documentation for that says this:

    The ID of the zone to search. Search results are limited to records in the specified zone. Specify nil to search the default zone of the database.

    It's the predicate that's wrong. It should be:

    NSPredicate(format: "nickName = %@", name)

    And one other thing, the performQuery will be executed asynchronous. So you are returning myRecord while it has not been set yet. You have 2 options.

    1. You could use semaphores to make this method synchronous.
    2. Instead of returning a value you could call the method while passing on a code block. Then call that code block with that record.

    Option 2 is the preferred method. Option 1 will lock your app during the CloudKit call.