[Implementation tips - ASMultiplexImageNode] ASCollectionView loading Images from Photo Library
I am trying to load Photos from Photo Library and the memory used by the app goes up by approximately 30MB per picture it loads from the library. I am using PHPhotoLibraryChangeObserver to observe changes to PhotoLibrary and PHCachingImageManager to get photos.
I am only loading thumbnails of pictures of size 512x512. I am reloading entire section using section reloadSection. Is there a better way to insert nodes inside a ASCollectionView?
Here is the code I added to CustomCollectionView Example:
extension ViewController: PHPhotoLibraryChangeObserver {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
updateCachedAssets()
}
override func viewWillAppear(_ animated: Bool) {
let scale = UIScreen.main.scale
let cellSize = (_collectionView?.collectionViewLayout as! UICollectionViewFlowLayout).itemSize
thumbnailSize = CGSize(width: cellSize.width * scale, height: cellSize.height * scale)
}
func initPHFetch() {
let allPhotosOptions = PHFetchOptions()
let p1 = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
let p2 = NSPredicate(format: "NOT ((mediaSubtype & %d) != 0)", PHAssetMediaSubtype.photoScreenshot.rawValue)
let p3 = NSPredicate(format: "creationDate > %@", Date() as CVarArg);
allPhotosOptions.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [p1,p2,p3] )
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
allPhotos = PHAsset.fetchAssets(with: allPhotosOptions)
}
func registerDelegates() {
resetCachedAssets()
PHPhotoLibrary.shared().register(self)
}
//Change Events
func photoLibraryDidChange(_ changeInstance: PHChange) {
guard let changes = changeInstance.changeDetails(for: allPhotos)
else { return }
// Update the cached fetch result.
allPhotos = changes.fetchResultAfterChanges
if changes.hasIncrementalChanges {
if let inserted = changes.insertedIndexes, inserted.count > 0 {
_ = inserted.map({
let i = self.getPhotoImage(index: $0)
_sections?[0].insert(i, at: 0)
})
DispatchQueue.global(qos: .userInteractive).async {
DispatchQueue.main.async(execute: {
**self._collectionView?.reloadSections([0])**
})
}
}
}
resetCachedAssets()
}
fileprivate func resetCachedAssets() {
imageManager.stopCachingImagesForAllAssets()
}
func getAssetThumbnail(asset: PHAsset, size: CGSize) -> UIImage {
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
imageManager.requestImage(for: asset, targetSize: size,
contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
func getPhotoImage(index: Int) -> UIImage {
let asset = self.allPhotos.object(at: index)
return self.getAssetThumbnail(asset: asset, size: CGSize(width: 512, height: 512))
}
// Call from viewDidAppear
fileprivate func updateCachedAssets() {
// Update only if the view is visible.
guard isViewLoaded && view.window != nil else { return }
// The preheat window is twice the height of the visible rect.
let preheatRect = view!.bounds.insetBy(dx: 0, dy: -0.5 * view!.bounds.height)
// Update only if the visible area is significantly different from the last preheated area.
let delta = abs(preheatRect.midY - previousPreheatRect.midY)
guard delta > view.bounds.height / 3 else { return }
// Compute the assets to start caching and to stop caching.
let (addedRects, removedRects) = differencesBetweenRects(previousPreheatRect, preheatRect)
let addedAssets = addedRects
.flatMap { rect in _collectionView!.indexPathsForElements(in: rect) }
.map { indexPath in allPhotos.object(at: indexPath.item) }
let removedAssets = removedRects
.flatMap { rect in _collectionView!.indexPathsForElements(in: rect) }
.map { indexPath in allPhotos.object(at: indexPath.item) }
// Update the assets the PHCachingImageManager is caching.
imageManager.startCachingImages(for: addedAssets,
targetSize: thumbnailSize, contentMode: .aspectFill, options: nil)
imageManager.stopCachingImages(for: removedAssets,
targetSize: thumbnailSize, contentMode: .aspectFill, options: nil)
// Store the preheat rect to compare against in the future.
previousPreheatRect = preheatRect
}
fileprivate func differencesBetweenRects(_ old: CGRect, _ new: CGRect) -> (added: [CGRect], removed: [CGRect]) {
if old.intersects(new) {
var added = [CGRect]()
if new.maxY > old.maxY {
added += [CGRect(x: new.origin.x, y: old.maxY,
width: new.width, height: new.maxY - old.maxY)]
}
if old.minY > new.minY {
added += [CGRect(x: new.origin.x, y: new.minY,
width: new.width, height: old.minY - new.minY)]
}
var removed = [CGRect]()
if new.maxY < old.maxY {
removed += [CGRect(x: new.origin.x, y: new.maxY,
width: new.width, height: old.maxY - new.maxY)]
}
if old.minY < new.minY {
removed += [CGRect(x: new.origin.x, y: old.minY,
width: new.width, height: new.minY - old.minY)]
}
return (added, removed)
} else {
return ([new], [old])
}
}
}
private extension UICollectionView {
func indexPathsForElements(in rect: CGRect) -> [IndexPath] {
let allLayoutAttributes = collectionViewLayout.layoutAttributesForElements(in: rect)!
return allLayoutAttributes.map { $0.indexPath }
}
}
Here is the short video of the memory growing with every photo. memoryIssue.mov.zip
Complete Project: CustomCollectionView.zip
Steps: Start the Project, Take couple of pictures from the camera and go back into the app... it will load new pictures and you'll see memory grow, which never comes back. If you take 10 new pictures, app will crash!
@rajeevwhiz your problem appears to be that you're fetching the image thumbnails as a data model - e.g. you are fetching the image data before the photos are near the screen, which uses a large amount of memory.
Instead, your ASImageNode(s) in each ASCellNode should be allowed to do this data fetching. If you write a custom class, you can override didEnterPreloadState and didExitPreloadState to perform this data loading and clearing to manage memory efficiently.
If you are integrating with the Apple Photos.framework, I suggest looking at ASMultiplexImageNode, which has native / built-in support for Photos library URLs. It does this loading for you automatically. You can configure the "tuningParameters" of the ASCollectionNode to load a different distance "ahead", both for loading the data and decoding the image, if you want to control memory usage in more detail.
I'm not too familiar with Swift <-> Obj-C interoperation, but you'll need to create an ASCellNode that contains an ASMultiplexImageNode (and handles its layout).
While testing this, please use the 2.0-beta.1 release. This is available via a git tag by that same name (see adoption specifics if you're using cocoapods here; it's also available via Carthage.) http://asyncdisplaykit.org/docs/adoption-guide-2-0-beta1.html
https://github.com/facebook/AsyncDisplayKit/releases/tag/2.0-beta.1
When using ASMultiplexImageNode, you should create it with just alloc/init — no need to provide a special downloader. http://asyncdisplaykit.org/docs/multiplex-image-node.html
Regarding how to insert nodes - yes, please use insertItemsAtIndexPaths: whenever possible. If you need to perform multiple operations (such as a delete and insert, or any other combination), you should wrap them in a performBatchUpdates: call. Check out the /docs page for more details and feel free to ask questions. @Adlai-Holler is an expert in Collection as well, and you may find him on Slack (Japan timezone)
@appleguy thanks for the direction and insights... I was completely lost!
I have started upgrading to ASDK 2.0 and will implement ASMultiplexImageNode as per your suggestions. I may come back with more clarification questions.
When migrating to ASDK2.0, I am seeing a conflict around ASStaticLayoutSpec. As per the conversion guide, ASStaticLayoutSpec has been renamed to ASAbsoluteLayoutSpec but it seems like it's not deprecated either. Should I change all ASStaticLayoutSpec to ASAbsoluteLayoutSpec?
I am also seeing errors for setChildren method which takes an array in 1.x but I can't find an equivalent method in 2.0
@rajeevwhiz Happy to answer your questions around conversion to 2.0:
ASStaticLayoutSpec: There are two options: You can either use ASWrapperLayoutSpec or use ASAbsoluteLayoutSpec with sizing option: ASAbsoluteLayoutSpecSizingSizeToFit instead of ASStaticLayoutSpec
setChildren: This is now a property so use .children = instead.
Let me know if this answers your questions.
thanks @maicki . I am fully on ASDK 2.0 now.. :)
@rajeevwhiz Awesome to hear!! I will close this issue for now, please reopen in case you think it's not resolved!
Thanks @maicki . I am now implementing the suggestions from @appleguy around ASMultiplexImageNode. I have implemented ASCellNode that contains an ASMultiplexImageNode as per his suggestion. Can you point me to some example project or sample code which uses ASMultiplexImageNode with Photo Library?
@appleguy @maicki How do I tie a ASMultiplexImageNode to a PHAsset?
@appleguy @maicki figured it out! I have to implement assetForLocalIdentifier.
Is there a way to mix images downloaded from network and from PhotoLibrary into the same collection? Or is it a bad idea?
I would imagine I should not be implementing urlForImageIdentifier and assetForLocalIdentifier for the same ASMultiplexImageNodeDataSource... Is it possible? If yes, how is the conflict resolved?
I guess I can implement two separate ASCellNodes to handle two use cases and add it to them to the same collection... Any recommendations?