我想知道为什么contentsOf从avurlaset返回nil作为URL。从带有照片框架的自定义库中选择后,我尝试从Phaset请求资源,如下所示:

PHCachingImageManager().requestAVAsset(forVideo: asset, options: nil) { (avAsset, _, _) in
 DispatchQueue.main.async {
 guard let asset = avAsset as? AVURLAsset else {
     return
 }
 print(asset.url) // file:///var/mobile/Media/DCIM/101APPLE/IMG_1513.MP4
  }
}

以上网址的视频可以用AVPlayer正常显示。但是,当我尝试使用以下方法获取与url相关联的数据时:
 do {
   let videoData = try Data(contentsOf: mediaURL!)
 } catch (let error){
     print(error.localizedDescription ?? "") // "The file “IMG_1490.MP4” couldn’t be opened because you don’t have permission to view it."
 }

最佳答案

请找到我从gallery检索最新视频的工作源代码,然后我使用我转换的AVURLAsset数据将该视频转换为AVURLAsset。
斯威夫特4

    override func viewDidLoad() {
        super.viewDidLoad()

        //For fetching Videos from Photo Library.
        let phFetchOptions = PHFetchOptions()
        phFetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",
                                                           ascending: false)]
        phFetchOptions.predicate = NSPredicate(format: "mediaType == %d",
                                               PHAssetMediaType.video.rawValue)
        phFetchOptions.fetchLimit = 2
        let videoPhAssetResult = PHAsset.fetchAssets(with:phFetchOptions)
        print(videoPhAssetResult.count)
        let videoPHAsset = videoPhAssetResult.object(at: 0)

        //For Fetching AvAsset from PHAsset and along with that getting Data from AvAsset
        PHCachingImageManager().requestAVAsset(forVideo:videoPHAsset , options: nil) { (vidAvAsset, _, _) in
            DispatchQueue.main.async {
                if vidAvAsset != nil {
                    let assetURL = vidAvAsset as? AVURLAsset
                    print(assetURL?.url)
                    do {
                        let videoData = try Data(contentsOf:(assetURL?.url)!)
                        print(videoData)
                    } catch (let error){
                        print(error.localizedDescription)
                    }
                }
            }

        }
    }

(注意:请不要忘记添加隐私-访问设备或模拟器照片库的照片库使用说明权限)

10-08 07:46