Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve the performance and speed of loading large numbers of assets #84

Merged
merged 4 commits into from
Aug 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ extension AssetsManager: PHPhotoLibraryChangeObserver {
let removedIndexes = removedIndexesSet.asArray().sorted(by: { $0.row < $1.row })
var removedAssets = [PHAsset]()
for removedIndex in removedIndexes.reversed() {
removedAssets.insert(assetArray.remove(at: removedIndex.row), at: 0)
// removedAssets.insert(assetArray.remove(at: removedIndex.row), at: 0)
// TODO: replace assetArray to fetchResult
}
// stop caching for removed assets
stopCache(assets: removedAssets, size: pickerConfig.assetCacheSize)
Expand All @@ -112,7 +113,8 @@ extension AssetsManager: PHPhotoLibraryChangeObserver {
for insertedIndex in insertedIndexes {
let insertedAsset = assetsChangeDetails.fetchResultAfterChanges.object(at: insertedIndex.row)
insertedAssets.append(insertedAsset)
assetArray.insert(insertedAsset, at: insertedIndex.row)
// assetArray.insert(insertedAsset, at: insertedIndex.row)
// TODO: replace assetArray to fetchResult
}
// start caching for inserted assets
cache(assets: insertedAssets, size: pickerConfig.assetCacheSize)
Expand Down
59 changes: 30 additions & 29 deletions AssetsPickerViewController/Classes/Assets/AssetsManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ open class AssetsManager: NSObject {
}
}

fileprivate let imageManager = PHCachingImageManager()
let imageManager = PHCachingImageManager()
fileprivate var authorizationStatus = PHPhotoLibrary.authorizationStatus()
var subscribers = [AssetsManagerDelegate]()

Expand All @@ -50,14 +50,14 @@ open class AssetsManager: NSObject {
var fetchedAlbumsArray = [[PHAssetCollection]]()
/// stores sorted array by applying user defined comparator, it's in decreasing order by count by default, and it might same as fetchedAlbumsArray if AssetsPickerConfig has albumFetchOptions without albumComparator
var sortedAlbumsArray = [[PHAssetCollection]]()
internal(set) open var assetArray = [PHAsset]()
internal(set) open var fetchResult: PHFetchResult<PHAsset>?

fileprivate(set) open var defaultAlbum: PHAssetCollection?
fileprivate(set) open var cameraRollAlbum: PHAssetCollection!
fileprivate(set) open var selectedAlbum: PHAssetCollection?

fileprivate var isFetchedAlbums: Bool = false
fileprivate var resourceLoadingQueue: DispatchQueue = DispatchQueue(label: "com.assetspicker.loader", qos: .userInitiated)
fileprivate var resourceLoadingQueue: DispatchQueue = DispatchQueue(label: "com.assetspicker.loader", qos: .default)

private override init() {
super.init()
Expand All @@ -82,7 +82,7 @@ open class AssetsManager: NSObject {
sortedAlbumsArray.removeAll()

// clear assets
assetArray.removeAll()
fetchResult = nil

// clear fetch results
albumsFetchArray.removeAll()
Expand Down Expand Up @@ -236,8 +236,9 @@ extension AssetsManager {
open func image(at index: Int, size: CGSize, isNeedDegraded: Bool = true, completion: @escaping ((UIImage?, Bool) -> Void)) -> PHImageRequestID {
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
guard let asset = fetchResult?.object(at: index) else { return PHInvalidImageRequestID }
return imageManager.requestImage(
for: assetArray[index],
for: asset,
targetSize: size,
contentMode: .aspectFill,
options: options,
Expand Down Expand Up @@ -318,13 +319,14 @@ extension AssetsManager {
return false
}
self.selectedAlbum = newAlbum
if let fetchResult = fetchMap[newAlbum.localIdentifier] {
let indexSet = IndexSet(0..<fetchResult.count)
assetArray = fetchResult.objects(at: indexSet)
return true
} else {
guard let album = AssetsManager.shared.selectedAlbum else {
return false
}
guard let fetchResult = AssetsManager.shared.fetchMap[album.localIdentifier] else {
return false
}
self.fetchResult = fetchResult
return true
}

open func selectDefaultAlbum() {
Expand All @@ -341,24 +343,20 @@ extension AssetsManager {
}
}

open func selectAsync(album newAlbum: PHAssetCollection, completion: @escaping (Bool, [PHAsset]) -> Void) {
open func selectAsync(album newAlbum: PHAssetCollection, completion: @escaping (Bool, PHFetchResult<PHAsset>?) -> Void) {
if let oldAlbumIdentifier = self.selectedAlbum?.localIdentifier, oldAlbumIdentifier == newAlbum.localIdentifier {
logi("Selected same album.")
completion(false, [])
completion(false, nil)
}
self.selectedAlbum = newAlbum
if let fetchResult = fetchMap[newAlbum.localIdentifier] {
resourceLoadingQueue.async { [weak self] in
let indexSet = IndexSet(0..<fetchResult.count)
let photos = fetchResult.objects(at: indexSet)
self?.assetArray = photos
DispatchQueue.main.async {
completion(true, photos)
}
}
} else {
completion(false, [])
guard let album = AssetsManager.shared.selectedAlbum else { completion(false, nil)
return
}
guard let fetchResult = AssetsManager.shared.fetchMap[album.localIdentifier] else { completion(false, nil)
return
}
self.fetchResult = fetchResult
completion(true, fetchResult)
}
}

Expand Down Expand Up @@ -515,18 +513,18 @@ extension AssetsManager {
}
}

open func fetchAssets(isRefetch: Bool = false, completion: (([PHAsset]) -> Void)? = nil) {
open func fetchAssets(isRefetch: Bool = false, completion: ((PHFetchResult<PHAsset>?) -> Void)? = nil) {

fetchAlbums(isRefetch: isRefetch, completion: { [weak self] _ in

guard let `self` = self else { return }
if isRefetch {
self.assetArray.removeAll()
self.fetchResult = nil
}

// set default album
self.selectAsync(album: self.defaultAlbum ?? self.cameraRollAlbum) { result, photos in
completion?(photos)
self.selectAsync(album: self.defaultAlbum ?? self.cameraRollAlbum) { successful, result in
completion?(result)
}
})

Expand All @@ -538,7 +536,10 @@ extension AssetsManager {
let albumFetchResult = PHAssetCollection.fetchAssetCollections(with: type, subtype: .any, options: fetchOption)
var fetchedAlbums = [PHAssetCollection]()

albumFetchResult.enumerateObjects({ (album, _, _) in
let indexSet = IndexSet(integersIn: 0..<albumFetchResult.count)
let albums = albumFetchResult.objects(at: indexSet)

for album in albums {
// fetch assets
self.fetchAlbum(album: album)

Expand All @@ -551,7 +552,7 @@ extension AssetsManager {
self.cameraRollAlbum = album
}
fetchedAlbums.append(album)
})
}

// get sorted albums
let sortedAlbums = self.sortedAlbums(fromAlbums: fetchedAlbums)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,18 @@ extension AssetsPhotoViewController {
completion(nil)
return
}
guard let savedAssetEntry = AssetsManager.shared.assetArray.enumerated().first(where: { $0.element.localIdentifier == newlySavedIdentifier }) else {
completion(nil)
var index: Int = NSNotFound
guard let fetchResult = AssetsManager.shared.fetchResult else { return }
fetchResult.enumerateObjects { (asset, idx, stop) in
if asset.localIdentifier == newlySavedIdentifier {
index = idx
stop.pointee = true
}
}
if index == NSNotFound {
return
}
let ip = IndexPath(row: savedAssetEntry.offset, section: 0)
let ip = IndexPath(row: index, section: 0)
indexPathToSelect = ip
if selectedArray.count < pickerConfig.assetsMaximumSelectionCount {
select(at: ip)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import Photos
extension AssetsPhotoViewController: UICollectionViewDataSource {

public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let count = AssetsManager.shared.assetArray.count
let count = AssetsManager.shared.fetchResult?.count ?? 0
updateEmptyView(count: count)
return count
}
Expand All @@ -23,11 +23,14 @@ extension AssetsPhotoViewController: UICollectionViewDataSource {
logw("Failed to cast UICollectionViewCell.")
return cell
}
let asset = AssetsManager.shared.assetArray[indexPath.row]
photoCell.asset = asset
photoCell.isVideo = asset.mediaType == .video
if photoCell.isVideo {
photoCell.duration = asset.duration
if let asset = AssetsManager.shared.fetchResult?.object(at: indexPath.row) {
photoCell.asset = asset
photoCell.isVideo = asset.mediaType == .video
if photoCell.isVideo {
photoCell.duration = asset.duration
}
} else {
photoCell.asset = nil
}
return cell
}
Expand All @@ -40,17 +43,20 @@ extension AssetsPhotoViewController: UICollectionViewDataSource {
return
}

let asset = AssetsManager.shared.assetArray[indexPath.row]
photoCell.asset = asset
photoCell.isVideo = asset.mediaType == .video
if photoCell.isVideo {
photoCell.duration = asset.duration
}

if let selectedAsset = selectedMap[asset.localIdentifier] {
if let targetIndex = selectedArray.firstIndex(of: selectedAsset) {
photoCell.count = targetIndex + 1
if let asset = AssetsManager.shared.fetchResult?.object(at: indexPath.row) {
photoCell.asset = asset
photoCell.isVideo = asset.mediaType == .video
if photoCell.isVideo {
photoCell.duration = asset.duration
}

if let selectedAsset = selectedMap[asset.localIdentifier] {
if let targetIndex = selectedArray.firstIndex(of: selectedAsset) {
photoCell.count = targetIndex + 1
}
}
} else {
photoCell.asset = nil
}

fetchService.cancelFetching(at: indexPath)
Expand Down Expand Up @@ -114,8 +120,10 @@ extension AssetsPhotoViewController: UICollectionViewDataSourcePrefetching {
public func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
var assets = [PHAsset]()
for indexPath in indexPaths {
if AssetsManager.shared.assetArray.count > indexPath.row {
assets.append(AssetsManager.shared.assetArray[indexPath.row])
let count = AssetsManager.shared.fetchResult?.count ?? 0
if count > indexPath.row {
guard let asset = AssetsManager.shared.fetchResult?.object(at: indexPath.row) else { return }
assets.append(asset)
}
}
AssetsManager.shared.cache(assets: assets, size: pickerConfig.assetCacheSize)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ extension AssetsPhotoViewController: UIViewControllerPreviewingDelegate {
guard let pressingCell = collectionView.cellForItem(at: pressingIndexPath) else { return nil }
previewingContext.sourceRect = pressingCell.frame
let previewController = AssetsPreviewController()
previewController.asset = AssetsManager.shared.assetArray[pressingIndexPath.row]
guard let fetchResult = AssetsManager.shared.fetchResult else { return nil }
previewController.asset = fetchResult.object(at: pressingIndexPath.row)
return previewController
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@ extension AssetsPhotoViewController {

func isSelected(at indexPath: IndexPath) -> Bool {
let manager = AssetsManager.shared
guard indexPath.row < manager.assetArray.count else { return false }
if let _ = selectedMap[manager.assetArray[indexPath.row].localIdentifier] {
guard let fetchResult = manager.fetchResult else { return false }
guard indexPath.row < fetchResult.count else { return false }
let asset = fetchResult.object(at: indexPath.row)
if let _ = selectedMap[asset.localIdentifier] {
return true
} else {
return false
Expand All @@ -47,8 +49,9 @@ extension AssetsPhotoViewController {
func select(at indexPath: IndexPath) {
defer { logSelectStatus(indexPath, isSelect: true) }
let manager = AssetsManager.shared
guard indexPath.row < manager.assetArray.count else { return }
let asset = manager.assetArray[indexPath.row]
guard let fetchResult = manager.fetchResult else { return }
guard indexPath.row < fetchResult.count else { return }
let asset = fetchResult.object(at: indexPath.row)
if let _ = selectedMap[asset.localIdentifier] {} else {
selectedArray.append(asset)
selectedMap[asset.localIdentifier] = asset
Expand All @@ -61,8 +64,9 @@ extension AssetsPhotoViewController {
func deselect(at indexPath: IndexPath) {
defer { logSelectStatus(indexPath, isSelect: false) }
let manager = AssetsManager.shared
guard indexPath.row < manager.assetArray.count else { return }
let asset = manager.assetArray[indexPath.row]
guard let fetchResult = manager.fetchResult else { return }
guard indexPath.row < fetchResult.count else { return }
let asset = fetchResult.object(at: indexPath.row)
guard let targetAsset = selectedMap[asset.localIdentifier] else {
logw("Invalid status.")
return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ extension AssetsPhotoViewController: UICollectionViewDelegate {
if LogConfig.isSelectLogEnabled { logi("shouldSelectItemAt: \(indexPath.row)") }

if let delegate = self.delegate {
let shouldSelect = delegate.assetsPicker?(controller: picker, shouldSelect: AssetsManager.shared.assetArray[indexPath.row], at: indexPath) ?? true
guard let fetchResult = AssetsManager.shared.fetchResult else { return false }
let shouldSelect = delegate.assetsPicker?(controller: picker, shouldSelect: fetchResult.object(at: indexPath.row), at: indexPath) ?? true
guard shouldSelect else { return false }
}

Expand Down Expand Up @@ -62,7 +63,8 @@ extension AssetsPhotoViewController: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
if LogConfig.isSelectLogEnabled { logi("shouldDeselectItemAt: \(indexPath.row)") }
if let delegate = self.delegate {
let shouldDeselect = delegate.assetsPicker?(controller: picker, shouldDeselect: AssetsManager.shared.assetArray[indexPath.row], at: indexPath) ?? true
guard let fetchResult = AssetsManager.shared.fetchResult else { return false }
let shouldDeselect = delegate.assetsPicker?(controller: picker, shouldDeselect: fetchResult.object(at: indexPath.row), at: indexPath) ?? true
guard shouldDeselect else { return false }
}
deselect(at: indexPath)
Expand All @@ -86,7 +88,8 @@ extension AssetsPhotoViewController {
return
}
for selectedIndexPath in indexPathsForSelectedItems {
if let _ = selectedMap[AssetsManager.shared.assetArray[selectedIndexPath.row].localIdentifier] {
guard let fetchResult = AssetsManager.shared.fetchResult else { return }
if let _ = selectedMap[fetchResult.object(at: selectedIndexPath.row).localIdentifier] {

} else {
loge("selected item not found in local map!")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,13 @@ extension AssetsPhotoViewController {
let manager = AssetsManager.shared
manager.subscribe(subscriber: self)
manager.fetchAlbums { _ in
manager.fetchAssets() { [weak self] photos in
manager.fetchAssets() { [weak self] result in
guard let `self` = self else { return }
self.updateEmptyView(count: photos.count)
guard let fetchResult = result else { return }
self.updateEmptyView(count: fetchResult.count)
self.updateNavigationStatus()
self.collectionView.reloadData()
self.preselectItemsIfNeeded(photos: photos)
self.preselectItemsIfNeeded(result: fetchResult)
self.scrollToLastItemIfNeeded()
// hide loading
self.loadingPlaceholderView.isHidden = true
Expand Down
Loading