iosswiftavfoundationphotokit

How to load images and videos in same UICollectionView in iOS


Plese refer to this pic

I am trying to have one collection view which can show all images and videos from camera roll based on time stamp .

i am able to load only images or only videos not both .

i have tried below code

        var photos: PHFetchResult<PHAsset>! // user photos array in collectionView for disaplying video thumnail 
        func getAssetFromPhoto() {
            let options = PHFetchOptions()
            options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: true) ]
            options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.video.rawValue)
            photos = PHAsset.fetchAssets(with: options)
            print(photos)
            photoCollectionView.reloadData() // reload your collectionView
        }

As you can see in above code snipped ,when defining options we can only ask for video collection or image collection .

How can i combine them both . Please note : i am open for any kind of development suggestion and as a workaround i am combining to PHFetchResult in one collection and populating my collection view .

Is this the only way ? or does Apple provide an api for the same .


Solution

  • Have you tried creating OR predicate?

    let videoPredicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.video.rawValue)
    let imagePredicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
    let predicate = NSCompoundPredicate(orPredicateWithSubPredicates: [videoPredicate, imagePredicate])
    
    options.predicate = predicate
    

    Or even, not providing a predicate at all. A predicate is used to filter results. If you don't want to filter the results just don't use a predicate.