Show assets immediately after granting permissions

This commit is contained in:
Shadowfacts 2021-04-04 15:04:32 -04:00
parent edd89450aa
commit a896573a5e
1 changed files with 41 additions and 13 deletions

View File

@ -69,6 +69,7 @@ class AssetCollectionViewController: UICollectionViewController {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed))
collectionView.alwaysBounceVertical = true
collectionView.allowsMultipleSelection = true
collectionView.register(UINib(nibName: "AssetCollectionViewCell", bundle: .main), forCellWithReuseIdentifier: reuseIdentifier)
collectionView.register(UINib(nibName: "ShowCameraCollectionViewCell", bundle: .main), forCellWithReuseIdentifier: cameraReuseIdentifier)
@ -97,19 +98,6 @@ class AssetCollectionViewController: UICollectionViewController {
}
})
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchResult = fetchAssets(with: options)
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.assets])
var items: [Item] = [.showCamera]
fetchResult.enumerateObjects { (asset, _, _) in
items.append(.asset(asset))
}
snapshot.appendItems(items)
dataSource.apply(snapshot, animatingDifferences: false)
collectionView.allowsMultipleSelection = true
setEditing(true, animated: false)
updateItemsSelectedCount()
@ -122,6 +110,12 @@ class AssetCollectionViewController: UICollectionViewController {
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadAssets()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
@ -137,6 +131,40 @@ class AssetCollectionViewController: UICollectionViewController {
}
}
private func loadAssets() {
switch PHPhotoLibrary.authorizationStatus(for: .readWrite) {
case .notDetermined:
PHPhotoLibrary.requestAuthorization(for: .readWrite) { (_) in
self.loadAssets()
}
return
case .restricted, .denied:
// todo: better UI for this
return
case .authorized, .limited:
// todo: show "add more" button for limited access
break
@unknown default:
// who knows, just try anyways
break
}
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchResult = fetchAssets(with: options)
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.assets])
var items: [Item] = [.showCamera]
fetchResult.enumerateObjects { (asset, _, _) in
items.append(.asset(asset))
}
snapshot.appendItems(items)
dataSource.apply(snapshot, animatingDifferences: false)
}
open func fetchAssets(with options: PHFetchOptions) -> PHFetchResult<PHAsset> {
return PHAsset.fetchAssets(with: options)
}