我正在使用CKQueryOperation获取CloudKit数据库。出于某种原因,每次我按下获取按钮时,第一次出现nil光标。它第二次获取并获取数据,一切都很好。当我检查recordFetchedBlock时,它确实会获取结果并将其追加,但是最后数组为空。我不明白为什么会这样。我想立即显示结果,因为它们已被获取。我认为问题出在nil光标上,但是我愿意接受其他建议。这是我的代码:
public class CloudKitDatabase {
static let shared = CloudKitDatabase()
var records = [CKRecord]()
let publicData = CKContainer.default().publicCloudDatabase
init() {
self.fetchRecords()
}
func fetchRecords() {
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "OECD", predicate: predicate)
let queryOperation = CKQueryOperation(query: query)
queryOperation.recordFetchedBlock = {
record in
self.records.append(record)
}
queryOperation.queryCompletionBlock = { cursor, error in
DispatchQueue.main.async {
if error != nil {
print(error.debugDescription)
} else {
if cursor != nil {
self.queryServer(cursor!)
} else {
print("CURSOR IS NIL")
}
}
}
}
self.publicData.add(queryOperation)
}
func queryServer(_ cursor: CKQueryOperation.Cursor) {
let queryOperation = CKQueryOperation(cursor: cursor)
queryOperation.recordFetchedBlock = {
record in
self.records.append(record)
}
queryOperation.queryCompletionBlock = { cursor, error in
DispatchQueue.main.async {
if error != nil {
print(error.debugDescription)
} else {
if cursor != nil {
self.queryServer(cursor!)
} else {
print("CURSOR IS NIL")
}
}
}
}
self.publicData.add(queryOperation)
}
调试区域告诉我:光标是零并且CloudKitDatabase.shared.records.isEmpty为true
首先在第一个查询上尝试一些配置;
let queryOperation = CKQueryOperation(query: query)
queryOperation.queuePriority = .veryHigh
queryOperation.resultsLimit = 99 // built in limit is 400
接下来,不要在调度中进行游标调用,而不要包含您的完成内容;
queryOperation.queryCompletionBlock =
{ cursor, error in
if error != nil {
print(error.debugDescription)
} else {
if cursor != nil {
self.queryServer(cursor!)
} else {
print("CURSOR IS NIL")
completion(nil)
}
}
}
和;
queryOperation.queryCompletionBlock =
{ cursor, error in
if error != nil {
print(error.debugDescription)
} else {
if cursor != nil {
self.queryServer(cursor!)
} else {
print("CURSOR IS NIL")
completion(nil)
}
}
}
也不要忘记在fetchRecords的开头清空记录数组,否则连续调用将在数组中获得相同的记录。