How to get NSData from file by using PHAsset

馋奶兔 提交于 2019-12-01 08:37:01

You can't access the NSURL directly as the files are outside of the sandbox of your app. Some frameworks (like AVPlayer) have exception entitlements and can access the URLs. To access the data of PHAsset objects take a look at the following methods of PHImageManager:

For images: requestImageDataForAsset

For videos: requestExportSessionForVideo

Maciek z Wrocławia

For me helped the following code. It's important to use relativePath instead of absoluteString.

    [[PHImageManager defaultManager] requestAVAssetForVideo:videoContent options:options resultHandler:^(AVAsset* avasset, AVAudioMix* audioMix, NSDictionary* info){
                AVURLAsset* myAsset = (AVURLAsset*)avasset;
                NSData * data = [NSData dataWithContentsOfFile:myAsset.URL.relativePath];       
                if (data) {
                }
    }];

Swift 3 version:-

PHImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (asset, mix, nil) in
                    let myAsset = asset as? AVURLAsset
                    do {
                        let videoData = try Data(contentsOf: (myAsset?.url)!)
                        self.selectedVideoData = videoData  //Set video data to nil in case of video
                        print("video data : \(videoData)")

                    } catch  {
                        print("exception catch at block - while uploading video")
                    }
                })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!