Swift fetch images and videos from camera roll

Rupshikha picture Rupshikha · Jul 6, 2016 · Viewed 10.4k times · Source

I am using "PHAsset" for fetching camera roll assets. I am using

PHAsset.fetchAssetsWithMediaType(.Image, options: options)

for fetching all gallery images. But I want to fetch all Images and Videos at a same time and show in a collection view (like Instagram camera view).

Can any one please tell me how can I do it?

Answer

Mehdi picture Mehdi · Dec 10, 2017

Actual Solution (swift 4 and probably swift 3): In your viewDidLoad or where ever is right for your case call checkAuthorizationForPhotoLibraryAndGet()

    private func getPhotosAndVideos(){

        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",ascending: false)]
        fetchOptions.predicate = NSPredicate(format: "mediaType = %d || mediaType = %d", PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue)
        let imagesAndVideos = PHAsset.fetchAssets(with: fetchOptions)
        print(imagesAndVideos.count)
    }

    private func checkAuthorizationForPhotoLibraryAndGet(){
        let status = PHPhotoLibrary.authorizationStatus()

        if (status == PHAuthorizationStatus.authorized) {
            // Access has been granted.
            getPhotosAndVideos()
        }else {
            PHPhotoLibrary.requestAuthorization({ (newStatus) in

                if (newStatus == PHAuthorizationStatus.authorized) {
                        self.getPhotosAndVideos()
                }else {

                }
            })
        }
    }

1) Make sure mediaType = %d is used instead of mediaType == %d

2) Make sure you actually have authorization and can access the photo library, otherwise it would fail silently.