Search code examples
iosuicollectionviewcloudkitckasset

Load CKAssets into UICollectionView async


Is there a way to load CKAsset photo into UICollectionView asynchronously ? At the moment, inside queryCompletionHandler from CKDatabase performQuery, I get list of CKRecords with CKAssets, and then set UICollectionView images to CKAsset.fileURL.path, which I then do [UICollectionView reload]

The reload takes a long time because it seems like it downloads all images at the same time. What I want to do is to use AsyncImageView (https://github.com/nicklockwood/AsyncImageView) to display placeholder while the real images are being downloaded.

Cannot see a way to use AsyncImageView (or any other library) to load CKAsset photos,

Any ideas ?


Solution

  • In your case your CKAsset files are directly linked to the CKRecords that you fetch for your table result. Because of that you will have the assets available the moment a result is returned. The availability of the files is directly linked to the returned records. There are 2 ways to make this look better.

    1. Use a perRecordCompletionBlock for a CKFetchRecordsOperation. Then when you execute your query all records will come in one by one. Each time a record comes in you can add it to your tableView. In this case you won't see the data until it's fetched. rows will be added one by one until you have all.

    2. Put each CKAsset in it's own CKRecord and add a reference in your original record to this asset record. Then query the original records to get the data without the assets and then for each cell start up a new fetch (will be async, so no need to do any magic, just set the cels image) to get the related asset record and then just the asset. The benefit of this approach is that you will see all the data in the tableview, but you won't see the related image until it's fetched.

    One note: When you set an image using CKAsset.fileURL.path, then you can only do that inside the CloudKit completion block. The url location is a CloudKit cache location. You will not be able to know how long that image will stay in that location. If you want to make sure the file remains available, you have to copy it over to your document folder.