是否可以实施批量提取'在cloudkit中,以便我可以调用一个方法来提取下一个X记录?目前,根据CloudKit Batch Fetches? cloudkit隐式处理这个问题,但我想以某种方式创建一种方法,允许我每次都提取指定数量的查询。 以下是我到目前为止的内容:(其中continuePullPosts与我发布的方法类似)
queryOP.recordFetchedBlock = { record in
//do stuff here
annotations.append(postToAdd)
}
queryOP.queryCompletionBlock = { [unowned self] (cursor, error) in
DispatchQueue.main.async {
if error == nil {
if completionHandler(annotations) {
if cursor != nil {
let newQueryOP = CKQueryOperation(cursor: cursor!)
self.continuePullPosts(curLocation: curLocation, queryOP: newQueryOP,
annotations: annotations, completionHandler: completionHandler)
}
}
} else {
print(error)
print("could not pull posts")
}
}
}
queryOP.resultsLimit = CKQueryOperationMaximumResults
CKContainer.default().publicCloudDatabase.add(queryOP)
}
答案 0 :(得分:0)
@Adolfo的回答让我有95%的答案,但是我遇到了一个问题:
每次我到达最后一页(或批处理)或数据时,它都会从数据集的开头开始向我发送数据。
这是一个问题,因为在我用完数据之后,我希望停止加载。
要解决此问题,我添加了一个参数来指定它是否是第一次获取。这使我只能在第一次获取时创建一个新查询。如果不是第一次获取,则不会进行任何新查询,并且将返回一个空数组。
public func fetchYourRecords(isFirstFetch: Bool, _ cursor: CKQueryCursor? = nil, completionHandler handler: @escaping YourFetchCompletionHandler) -> Void {
var result: [CKRecord] = [CKRecord]()
let queryOP: CKQueryOperation
if isFirstFetch {
// Create the operation for the first time
queryOP = CKQueryCursor(query:...)
} else if let cursor = cursor {
// Operation to fetch another 10 records.
queryOP = CKQueryOperation(cursor: cursor)
} else {
// If not first time and if cursor is nil (which means
// there is no more data) then return empty array
// or whatever you want
handler([], nil)
return
}
queryOp.recordFetchedBlock = { (record: CKRecord) -> Void in
result.append(record)
}
queryOP.queryCompletionBlock = { [unowned self] (cursor, error) in
handler(result, cursor)
}
// Fetch only 10 records
queryOP.resultsLimit = 10
CKContainer.default().publicCloudDatabase.add(queryOP)
}