繁体   English   中英

Swift 自定义图像选择器 controller - 第一次不加载媒体

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

我正在尝试实现自定义图像选择器 Controller,或者更确切地说是视频选择器 controller,这是获取照片库中所有视频的代码:

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)
            })
        })
    }
}

很明显,这需要用户的权限才能访问照片库,并且我们第一次这样做时会弹出警告让用户授予权限。

但是,在获得许可后,controller 实际上并没有开始加载视频。 我需要关闭 controller 并第二次代表它(当已经获得许可时)才能开始正确加载视频。

问题:如何在获得许可后立即正确加载视频,而不必再次关闭并呈现它(就像内置的UIImagePickerController

这可以通过检查是否有授权来完成,如果没有,则使用带有完成处理程序的PHPhotoLibrary.requestAuthorization来监视结果。

像这样:

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

请检查这个有代码的链接: -

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
                }
            })
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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