diff --git a/Tusker/CoreData/MastodonCachePersistentStore.swift b/Tusker/CoreData/MastodonCachePersistentStore.swift index a062a1933b..b055d11980 100644 --- a/Tusker/CoreData/MastodonCachePersistentStore.swift +++ b/Tusker/CoreData/MastodonCachePersistentStore.swift @@ -530,11 +530,34 @@ class MastodonCachePersistentStore: NSPersistentCloudKitContainer { defer { PersistentHistoryTokenStore.setToken(token, for: accountInfo) } - let req = NSPersistentHistoryChangeRequest.fetchHistory(after: lastToken) - if let result = try? self.remoteChangesBackgroundContext.execute(req) as? NSPersistentHistoryResult, - let transactions = result.result as? [NSPersistentHistoryTransaction], - !transactions.isEmpty { + let transactions: [NSPersistentHistoryTransaction] + do { + let req = NSPersistentHistoryChangeRequest.fetchHistory(after: lastToken) + if let result = try self.remoteChangesBackgroundContext.execute(req) as? NSPersistentHistoryResult { + transactions = result.result as? [NSPersistentHistoryTransaction] ?? [] + } else { + logger.error("Unexpectedly non-NSPersistentHistoryResult") + return + } + } catch { + logger.error("Unable to fetch persistent history results: \(String(describing: error), privacy: .public)") + return + } + if !transactions.isEmpty { self.processPersistentHistoryTransactions(transactions) + + do { + // delete history only before the last token, because we don't want to invalidate + // the most recent token + let deleteReq = NSPersistentHistoryChangeRequest.deleteHistory(before: lastToken) + let result = try self.remoteChangesBackgroundContext.execute(deleteReq) + if let result = result as? NSPersistentHistoryResult, + result.resultType == .statusOnly { + logger.info("Delete old persistent history result status: \(result.result as! Int)") + } + } catch { + logger.error("Unable to delete old persistent history: \(String(describing: error), privacy: .public)") + } } } }