简体   繁体   中英

Swift custom image picker controller - does not load media for the first time

I'm trying to implement a custom Image Picker Controller, or rather a video picker controller, here is the code for fetching all videos in photo library:

fileprivate func fetchVideos() {

    let allVideos = PHAsset.fetchAssets(with: .video, options: assetsFetchOptions())

    DispatchQueue.global(qos: .background).async {
        allVideos.enumerateObjects({ (asset, count, stop) in
            let imageManager = PHImageManager.default()

            imageManager.requestAVAsset(forVideo: asset, options: nil, resultHandler: { (asset, audioMix, info) in
                guard let asset = asset as? AVURLAsset, let image = asset.previewImage() else { return }

                print("Got a video: \(asset.duration.cmTimeString)")
//                  let medium = Medium(previewImage: image, duration: asset.duration)
//                  self.media.append(medium)
            })
        })
    }
}

Very obviously, this needs user's permission to access the photo library, and for the first time we do this it will pop up the alert for the user to give permission.

However, after given permission, the controller does not actually start to load the videos. I need to dismiss the controller and represent it for the second time (when the permission was already give) in order to start to load the video properly.

Question: how to load videos properly immediately after being given the permission without having to dismiss and present it for a second time (just like the built-in UIImagePickerController ?

This can be done by checking if there is authorization and if not, using the PHPhotoLibrary.requestAuthorization with completion handler to monitor the result.

Something like this:

    if PHPhotoLibrary.authorizationStatus() == .authorized {
        // Load image/ video function
    } else {
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                // Load image/ video function
            } else {
                // Show error message
            }
        }
    }

please check this link which has code:-

https://github.com/VishveshLad/VLCustomImagePicker/blob/main/CustomImagePicker/CustomImagePicker/CustomImagePickerVC.swift

if PHPhotoLibrary.authorizationStatus() == .authorized {
        //load data
        } else {
            PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) -> Void in
                if status == .authorized {
                    //load data
                } else {
                    // show error
                }
            })
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM