I am trying to fetch asset from local identifier and displaying images in collectionview but it makes scroll jerkiness

3.6k views Asked by At

I am trying following method to fetch asset from local identifier and displaying it in collection view but scroll become jerky while loading.

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GridCell", for: indexPath) as! GridCell

    cell.representedAssetIdentifier = "some uri"

        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = false
    let asset = PHAsset.fetchAssets(withLocalIdentifiers: ["some uri"!], options: .none).firstObject

    imageManager.requestImage(for: asset!, targetSize: thumbnailSize, contentMode: .aspectFit, options: requestOptions, resultHandler: { result, info in
        if cell.representedAssetIdentifier =="someuri" {

             cell.imageview.image = result

        }
    })
2

There are 2 answers

0
torinpitchers On

expensive operations should not be performed in the cellForItemAt method. The choppyness is because scrolling is delayed till that method has completed. This is specifically cause by the line:

let asset = PHAsset.fetchAssets(withLocalIdentifiers: ["some uri"!], options: .none).firstObject

remove that line and you will see that scrolling will be as smooth as butter. To fix this you need to be smarter about where and when that line gets executed if its reusable then do it once on viewDidLoad and store it as a variable.

0
HackaZach On

The PHAsset.fetchAssets( .. ) call happens synchronously, which blocks rendering of the collectionView and will make scrolling stutter. For smooth scrolling, always fetch assets asynchronously to not block the main thread.

For loading PHAssets, suggest looking at the PHImageManager class provided by Cocoa Touch.