我想检查具有某个谓词的记录是否存在,如果不存在,则执行以下操作:
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
似乎不会运行。
发布于 2020-10-07 15:46:47
这里的问题是,只有在获得记录时才会调用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
}
}
https://stackoverflow.com/questions/64236075
复制相似问题