I want to delete the object from the snapshot using swipe to delete, but first I need to make a network call which is located in view model. If the result is success, then remove the object, otherwise do nothing.
I am using custom view model class for fetching data and appending sections and items and I would also prefer that view model handles all network calls. Putting network call in tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) is not an option.
This is an example:
import UIKit
struct MySectionType: Hashable {}
struct MyItemType: Hashable {}
class MyViewModel {
func deleteItem(item: MyItemType) {
// Network call...
}
}
class MyViewController: UIViewController {
var viewModel: MyViewModel
// MARK: - Initialization
init?(coder: NSCoder, viewModel: MyViewModel) {
self.viewModel = viewModel
super.init(coder: coder)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
class DataSource: UITableViewDiffableDataSource<MySectionType, MyItemType> {
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if let item = itemIdentifier(for: indexPath) {
// Call viewModel deleteItem
// viewModel.deleteItem(item: item)
// If success - deleteItems
var snapshot = self.snapshot()
snapshot.deleteItems([item])
apply(snapshot)
}
}
}
}
}