For an unknown reason, when I delete a record in my app, the CloudKit record does not delete. So the next time the app runs, the “deleted” records come back.
I add the records as follows:
func addReadingListBook (book: NYTBook, list: ReadingList) {
//set it
var bookToAdd = RLBook(nytBook: book)!
let parentReference = CKRecord.Reference(recordID: list.recordId!, action: .none)
bookToAdd.parentReference = parentReference //needed for query
bookToAdd.record.parent = parentReference //needed for sharing
myReadingListBooksDictionary[book.primaryIsbn13] = bookToAdd
Task {
do {
// Save the RLBook record first
let savedBookRecord = try await db.save(bookToAdd.record)
// Persist related buy links as child records in CloudKit (if any)
if let links = book.buyLinks, !links.isEmpty {
var buyLinkRecords: [CKRecord] = []
for link in links {
let buyLinkRecordID = CKRecord.ID(zoneID: savedBookRecord.recordID.zoneID)
let buyLinkRecord = CKRecord(recordType: "BuyLink", recordID: buyLinkRecordID)
buyLinkRecord["parentReference"] = CKRecord.Reference(recordID: savedBookRecord.recordID, action: .deleteSelf)
buyLinkRecord["bookIsbn13"] = book.primaryIsbn13
buyLinkRecord["name"] = link.name
buyLinkRecord["url"] = link.url
buyLinkRecords.append(buyLinkRecord)
}
if !buyLinkRecords.isEmpty {
_ = try await db.modifyRecords(saving: buyLinkRecords, deleting: [])
}
}
} catch {
Logger.errorLog.error("\(error.localizedDescription)")
}
}
}
I delete the record like this:
func removeReadingListBook (book: RLBook) {
myReadingListBooksDictionary.removeValue (forKey: book.primaryIsbn13)
Task {
do {
// Delete related BuyLink records for this book
let parentRef = CKRecord.Reference(recordID: book.record.recordID, action: .deleteSelf)
let linkPredicate = NSPredicate(format: "parentReference == %@", parentRef)
let linkQuery = CKQuery(recordType: "BuyLink", predicate: linkPredicate)
let linkResult = try await db.records(matching: linkQuery, inZoneWith: book.record.recordID.zoneID)
let linkRecordIDs: [CKRecord.ID] = linkResult.matchResults.compactMap { try? $0.1.get().recordID }
if !linkRecordIDs.isEmpty {
_ = try await db.modifyRecords(saving: [], deleting: linkRecordIDs)
}
// Now delete the book record itself
try await db.deleteRecord(withID: book.record.recordID)
} catch {
Logger.errorLog.error("\(error.localizedDescription)")
}
}
}
I have checked role permissions and everything else I can think of or find on the internet. Any help would be appreciated.