Is it possible to track history using HistoryDescriptor in SwiftData?

Is it possible to track history using the new HistoryDescriptor feature in SwiftData? Or can I only get the current most recent data? Or is it possible to output the changed data itself, along with timestamps?

I am hoping that it is possible to track by a standard feature like NSPersistentHistoryTransaction in CoreData.

Do we still have to use a method in SwiftData that creates more tracking data itself?

Answered by DTS Engineer in 805269022

This seems to have been answered in the following post:

HistoryTransaction in SwiftData is pretty much the same as NSPersistentHistoryTransaction in Core Data. Neither of the APIs keep the changed data for an update.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

This seems to have been answered in the following post:

HistoryTransaction in SwiftData is pretty much the same as NSPersistentHistoryTransaction in Core Data. Neither of the APIs keep the changed data for an update.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

"So we can use historical information to manage history by saving and restoring tokens?"

I am unclear what "manage history by saving and restoring tokens" in the your comment really means, but the way to use SwiftData history is demonstrated in the Adopting SwiftData for a Core Data app sample.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

So the following CoreData can also be written as SwiftData?

func fetchPersistentHistory() {
        let context = persistentContainer.newBackgroundContext()
        context.perform {
            let lastToken = self.loadLastToken()
            
            let request = NSPersistentHistoryChangeRequest.fetchHistory(after: lastToken)
            if let result = try? context.execute(request) as? NSPersistentHistoryResult,.
               let transactions = result.result as? [NSPersistentHistoryTransaction] {
                
                for transaction in transactions {
                    self.process(transaction: transaction)
                }
                
                self.saveLastToken(from: transactions.last)
            }
        }
    }

 private func process(transaction: NSPersistentHistoryTransaction) {
        let context = persistentContainer.viewContext
        context.perform {
            transaction.changes?.forEach { change in
                if change.changedObjectID.entity.name == “MyEntity” {
                    self.applyChanges(from: change)
                }
            }
        }
    }

private func applyChanges(from change: NSPersistentHistoryChange) {
        switch change.changeType {
        case .insert:.
            self.restoreEntity(for: change.changedObjectID)
        case .update: self.updateEntity(for: changedObjectID)
            self.updateEntity(for: change.changedObjectID)
        case .delete: self.deleteEntity(for: change.changedObjectID)
            self.deleteEntity(for: change.changedObjectID)
        default: break
            break
        }
        
        // record changes in MyEntityHistory
        if let entityID = change.changedObjectID.uriRepresentation().absoluteString.components(separatedBy: “/”).last {
            addHistoryRecord(entityID: entityID, changeType:. “\(change.changeType)")
        }
        
        // Refresh the entity list after applying changes
        fetchEntities()
    }

    func addHistoryRecord(entityID: String, changeType: String) {
        let context = persistentContainer.viewContext
        let historyRecord = MyEntityHistory(context: context)
        historyRecord.id = UUID()
        historyRecord.entityID = entityID
        historyRecord.timestamp = Date()
        historyRecord.changeType = changeType
        
        do {
            try context.save()
        } catch {
            print("Failed to save history record:. \(error)")
        }
    }

Yeah, the sample mentioned in my previous post demonstrates how to persist and retrieve a history token via UserDefaults, and use the token to process the store history. Conceptually, it is pretty much the same as what you would do with the history token in Core Data.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Is it possible to track history using HistoryDescriptor in SwiftData?
 
 
Q