CloudKit 未获取新插入的记录
我正在使用 CloudKit 将数据插入数据库。初始提取工作正常,但是当我添加新记录并尝试再次提取所有记录时,它会忽略最后插入的记录。如果我再次运行该应用程序,我新创建的记录将正确显示。所以,问题是为什么我在插入全新记录后无法获取所有记录。
func saveItem(title: String, price: Decimal) {
let record = CKRecord(recordType: RecordType.itemListing.rawValue)
let itemListing = ItemListing(title: title, price: price)
record.setValuesForKeys(itemListing.toDictionary())
self.database.save(record) { newRecord, error in
if let error = error {
print(error)
} else {
// get all items from CloudKit
self.populateItems()
}
}
}
func populateItems() {
var items: [ItemListing] = []
let query = CKQuery(recordType: RecordType.itemListing.rawValue, predicate: NSPredicate(value: true))
database.fetch(withQuery: query) { result in
switch result {
case .success(let result):
print(result.matchResults)
result.matchResults.compactMap { $0.1 }
.forEach {
switch $0 {
case .success(let record):
if let itemListing = ItemListing.fromRecord(record) {
items.append(itemListing)
}
case .failure(let error):
print(error)
}
}
DispatchQueue.main.async {
self.items = items.map(ItemViewModel.init)
}
case .failure(let error):
print(error)
}
}
}
I am using CloudKit to insert data into the database. The initial fetch works fine but when I add a new record and try to fetch all records again, it ignores the last inserted record. If I run the app again, my newly created record shows up correctly. So, the question is why I am not able to get all the records after inserting a brand new record.
func saveItem(title: String, price: Decimal) {
let record = CKRecord(recordType: RecordType.itemListing.rawValue)
let itemListing = ItemListing(title: title, price: price)
record.setValuesForKeys(itemListing.toDictionary())
self.database.save(record) { newRecord, error in
if let error = error {
print(error)
} else {
// get all items from CloudKit
self.populateItems()
}
}
}
func populateItems() {
var items: [ItemListing] = []
let query = CKQuery(recordType: RecordType.itemListing.rawValue, predicate: NSPredicate(value: true))
database.fetch(withQuery: query) { result in
switch result {
case .success(let result):
print(result.matchResults)
result.matchResults.compactMap { $0.1 }
.forEach {
switch $0 {
case .success(let record):
if let itemListing = ItemListing.fromRecord(record) {
items.append(itemListing)
}
case .failure(let error):
print(error)
}
}
DispatchQueue.main.async {
self.items = items.map(ItemViewModel.init)
}
case .failure(let error):
print(error)
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论