frenzy-ios/Reader/Screens/Items/ItemsViewController.swift

79 lines
3.1 KiB
Swift

//
// ItemsViewController.swift
// Reader
//
// Created by Shadowfacts on 1/9/22.
//
import UIKit
import CoreData
class ItemsViewController: UIViewController {
let fervorController: FervorController
let fetchRequest: NSFetchRequest<Item>
private var collectionView: UICollectionView!
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var resultsController: NSFetchedResultsController<Item>!
init(fervorController: FervorController, fetchRequest: NSFetchRequest<Item>) {
self.fervorController = fervorController
self.fetchRequest = fetchRequest
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let configuration = UICollectionLayoutListConfiguration(appearance: .plain)
let layout = UICollectionViewCompositionalLayout.list(using: configuration)
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.register(ItemCollectionViewCell.self, forCellWithReuseIdentifier: "itemCell")
view.addSubview(collectionView)
dataSource = createDataSource()
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.items])
dataSource.apply(snapshot, animatingDifferences: false)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "published", ascending: false)]
resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: fervorController.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
resultsController.delegate = self
try! resultsController.performFetch()
}
private func createDataSource() -> UICollectionViewDiffableDataSource<Section, Item> {
let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { collectionView, indexPath, item in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "itemCell", for: indexPath) as! ItemCollectionViewCell
cell.updateUI(item: item)
return cell
}
return dataSource
}
}
extension ItemsViewController {
enum Section: Hashable {
case items
}
}
extension ItemsViewController: NSFetchedResultsControllerDelegate {
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {
var snapshot = self.dataSource.snapshot()
snapshot.deleteItems(snapshot.itemIdentifiers(inSection: .items))
// use resultsController here instead of controller so we don't have to cast
snapshot.appendItems(resultsController.fetchedObjects!, toSection: .items)
self.dataSource.apply(snapshot, animatingDifferences: false)
}
}