Ok, I've got a preliminary working version of a collectionview with a diffable datasource. All is working and I just implemented adding and changing items, and deleting items still to be done. There is little information out there as of current on adding, changing and deleting items with a diffable datasource. I wonder if all the array stuff I do is the way to go. I feel I should do more with the snapshot. Should all logic from the save method be in the update method? Any help appreciated and/or any resources on the matter
ProjectsViewController: UIViewController {
(...)
//DataSource methods (snapshot)
func updateData(on projects: [Project]) {
var snapshot = NSDiffableDataSourceSnapshot<Section, Project>()
snapshot.appendSections([Section.normal])
snapshot.appendItems(projects)
//apply() is safe to call from a background queue!
self.dataSource.apply(snapshot, animatingDifferences: true)
}
(...)
}
//MARK: - ProjectHandler (delegation method)
extension ProjectsViewController: ProjectHandler {
func save(_ project: Project, withImage image: UIImage?) {
//Make sure LastEdited Date gets updated
var projectToBeSaved = project
projectToBeSaved.lastEdited = Date()
//Current state
var projects = dataSource.snapshot().itemIdentifiers
//Replace the changed project
if projects.contains(projectToBeSaved) {
let index = projects.firstIndex(of: projectToBeSaved)
projects.remove(at: index!)
projects.append(projectToBeSaved)
//Add the new projects
} else {
projects.append(projectToBeSaved)
}
//sort on lastly edited
projects.sort { $0.lastEdited > $1.lastEdited }
//TODO: - Write to json
//update the snapshot
updateData(on: projects)
collectionView.reloadData()
}
}