Public 云数据库查询在应该的时候没有 return nil

Public cloud database query doesn't return nil when it should

我想检查是否存在具有特定谓词的记录,如果不存在,则执行某些操作:

let publicDatabase = CKContainer.default().publicCloudDatabase
let predicate: NSPredicate!
predicate = NSPredicate(format: "username == %@", usernameText)
let query =  CKQuery(recordType: "user", predicate: predicate)
let configuration = CKQueryOperation.Configuration()
configuration.allowsCellularAccess = true
configuration.qualityOfService = .userInitiated

let queryOperation = CKQueryOperation(query: query)
queryOperation.desiredKeys = ["username"]
queryOperation.queuePriority = .veryHigh
queryOperation.configuration = configuration
queryOperation.resultsLimit = 1
queryOperation.recordFetchedBlock = { (record: CKRecord?) -> Void in
    if let record = record {
    // #1
        print("record \(record)")
    } else {
    // #2
        print("none exists")
    }
}

queryOperation.queryCompletionBlock = { (cursor: CKQueryOperation.Cursor?, error: Error?) -> Void in
    if let error = error {
        print("\(error)")
        return
    }
    
    if let cursor = cursor {
        print("cursor: \(cursor)")
    }
}

publicDatabase.add(queryOperation)

当匹配谓词的记录存在时,该记录将按原样返回,但当它不存在时,甚至 nil 都不会返回让我做出相应的反应。我的意思是理想情况下我想在#2 中执行我的代码以响应不存在的任何记录,但 recordFetchedBlock 在这种情况下似乎 运行。

这里的问题是 recordFetchedBlock 仅在您获取记录时调用。没有记录?那么它就不会被调用。以下方法应该可以解决问题:

//define an array to store all records
var allRecords = []

queryOperation.recordFetchedBlock = { record in
    //called once for each record
    //if no results, then it is never called
    //if you get a record, add to the array
    allRecords.append[record]
}

//the query completion block is called at the end of the query (or when all results can't be returned in one block, then called with non-nil cursor value.  Considering that out of scope for this answer.
queryOperation.queryCompletionBlock = { (cursor: CKQueryOperation.Cursor?, error: Error?) in
    if let error = error {
        //handle error
    }
    if let cursor = cursor {
       //handle cursor if exists    
    } 
    if allRecords.count == 0 {
        //my query returned no results
        //take desired action    
    }
}