Dennis van Mazijk
Dennis van Mazijk

Reputation: 205

Swift - Fetch photos from album in CollectionView and keep resolution

I have a UICollectionView in which I load all of the user's photos from the photo album. All of the photos are fetched and stored in an array when the user opens the controller. Tapping a photo will create a subview with a black background and a bigger version of that photo. Tapping it again will remove it from the superView with a zoom-out transition.

My problem is that I don't know how to keep the original size of the photo as well as maintain a low execution time. Having 100+ photos load into a collection really hurts my load time.

I don't think it's necessary to fetch the pictures at a higher CGSize, because I actually want it to be the bounds of the cell (I have three cells per row).

Fetching images at 250 by 250 returns a 0.20 second execution time

Fetching images at 300 by 300 returns a 3.0 seconds execution time

What I want to achieve is to keep a very low execution time, have crisp thumbnails and a high resolution version of that photo when tapped. Do I have to create a second thread to load everything in the background or is it better to not call my function in my viewDidLoad?

var imageArray = [UIImage]()

func getPhotosFromAlbum() {

    let imageManager = PHImageManager.default()

    let requestOptions = PHImageRequestOptions()
    requestOptions.isSynchronous = true
    requestOptions.deliveryMode = .highQualityFormat

    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    let fetchResult: PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)

        if fetchResult.count > 0 {

            for i in 0..<fetchResult.count {

                imageManager.requestImage(for: fetchResult.object(at: i), targetSize: CGSize(width: 300, height: 300), contentMode: .aspectFill, options: requestOptions, resultHandler: { image, error in

                    self.imageArray.append(image!)
                })
            }
        } else {
                self.collectionView?.reloadData()
    }
}

Upvotes: 2

Views: 1014

Answers (1)

Fahim
Fahim

Reputation: 3556

Generally, if you are doing some heavy processing, it is better to do it in a background thread so that you don't lock up your main thread or make UI interaction sluggish. Of course, in that case, do remember to do any UI updates on the main thread.

Upvotes: 2

Related Questions