I'm using [PHCachingImageManager] to cache videos in a collection view. I can display the images generated with the cache manager, but pulling AVAssets isn't working.
I try to get an AVAsset by using the .requestAVAsset(forVideo:...) method but the [asset] that is returned to the result handler is nil. I get an error when trying to unwrap the returned [asset].
I also looked at the [audioMix] and [info] parameters returned to the result handler and they were nil was well. Does anyone know what I'm doing wrong/missing here?
viewDidLoad() {
let videosAlbum = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumVideos, options: nil)
self.videoAssets = PHAsset.fetchAssets(in: videosAlbum.object(at: 0), options: nil)
self.imgCacheManager.startCachingImages(for: self.videoAssets.objects(at: [0, videoAssets.count-1]), targetSize: CGSize(width: 150, height: 150), contentMode: .aspectFit, options: nil)
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedAsset = self.imgCacheManager.requestAVAsset(forVideo: self.videoAssets.object(at: indexPath.item), options: nil, resultHandler: {
asset,_,_ in
self.delegate.selectedVideo(Asset: asset!) // this is the line I get the error
})
}
My delegate is an optional but for sure has something in it, so I'm confident it's the unwrapped [asset] that's throwing the error.
It looks like I was trying to request video assets that were stored in iCloud without setting the video request options to allow network access.
When requesting the video from the PHCachingImageManager, I failed to pass any PHVideoRequestOptions object. Adding the lines below just prior to requesting the asset fixes this.
let options = PHVideoRequestOptions()
options.isNetworkAccessAllowed = true
I found this thread on an open source image picker using the Photos framework. The videos I was testing with were indeed in iCloud which caused my returned asset to be nil. The linked thread also has a good example of hooking up a progress handler in objective C:
options.networkAccessAllowed = YES;
options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info)
{
...
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With