Skip to content

Commit

Permalink
Reset with first album when there're no album after user granted some…
Browse files Browse the repository at this point in the history
… of them
  • Loading branch information
MarkRunWu committed Mar 30, 2021
1 parent 10bccd9 commit 851f8f2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions Sources/Controller/ImagePickerController+Albums.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ extension ImagePickerController: AlbumsViewControllerDelegate {
}

func select(album: PHAssetCollection) {
self.currentAlbum = album
assetsViewController.showAssets(in: album)
albumButton.setTitle((album.localizedTitle ?? "") + " ", for: .normal)
albumButton.sizeToFit()
Expand Down
33 changes: 32 additions & 1 deletion Sources/Controller/ImagePickerController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ import Photos
let dropdownTransitionDelegate = DropdownTransitionDelegate()
let zoomTransitionDelegate = ZoomTransitionDelegate()

lazy var albums: [PHAssetCollection] = {
private func loadAlbums() -> [PHAssetCollection] {
// We don't want collections without assets.
// I would like to do that with PHFetchOptions: fetchOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0")
// But that doesn't work...
Expand All @@ -74,6 +74,11 @@ import Photos
let assetsFetchResult = PHAsset.fetchAssets(in: $0, options: fetchOptions)
return assetsFetchResult.count > 0
}
}
var currentAlbum: PHAssetCollection?

lazy var albums: [PHAssetCollection] = {
self.loadAlbums()
}()

public init(selectedAssets: [PHAsset] = []) {
Expand All @@ -86,6 +91,16 @@ import Photos
fatalError("init(coder:) has not been implemented")
}

open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
PHPhotoLibrary.shared().register(self)
}

open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}

public override func viewDidLoad() {
super.viewDidLoad()

Expand Down Expand Up @@ -161,3 +176,19 @@ import Photos
albumButton.isHidden = albums.count < 2
}
}

extension ImagePickerController: PHPhotoLibraryChangeObserver {
public func photoLibraryDidChange(_ changeInstance: PHChange) {
if let currentAlbum = currentAlbum,
changeInstance.changeDetails(for: currentAlbum) != nil {
return
}
DispatchQueue.main.async {
self.albums = self.loadAlbums()
self.updateAlbumButton()
if let firstAlbum = self.albums.first {
self.select(album: firstAlbum)
}
}
}
}

0 comments on commit 851f8f2

Please sign in to comment.