簡體   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