1

I wonder why the contentsOf returns nil for URL from AVURLAsset. After picking from the custom library with Photos framework, I tried to request the asset from PHAsset like the following:

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

The video with the URL above can be displayed normally with AVPlayer. But when I try to get the data associated with the url using:

 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."
 }
Kesong Xie
  • 1,316
  • 3
  • 15
  • 35

1 Answers1

0

Please find working source code in which i have retrieved recent video from gallery then i have converted that video into AVURLAsset using that AVURLAsset i converted it's data.

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

        }
    }

(Note : Please don’t forget to add Privacy - Photo Library Usage Description permission for Accessing Photo Library of Device or Simulator)