How to get NSData from a file using PHAsset

I have a file in the path

file:///var/mobile/Media/DCIM/100APPLE/IMG_0197.mov 

But when I try this code -

 NSError *error; NSData *data = [NSData dataWithContentsOfFile:assetUrl.relativePath options:NSDataReadingMappedAlways error:&error]; 

I only got the error:

Domain error = NSCocoaErrorDomain Code = 257 "The operation could not be completed. (Cocoa, error 257)" UserInfo = 0x175a61380 {NSFilePath = / var / mobile / media / DCIM / 100APPLE / IMG_0197.mov, NSUnderlyingError = 0x17424e550 "The operation could not be completed. Operation not allowed "}

The file exists, but I cannot read it.

But at the same time, AVPlayer usually plays the video file.

I tried

 PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[assetUrl] options:nil]; 

But I did not get any result.

+3
source share
2 answers

You cannot access NSURL directly, because the files are outside the sandbox of your application. Some structures (for example, AVPlayer ) have exclusion rights and can access URLs. To access PHAsset object PHAsset , view the following PHImageManager methods:

For images: requestImageDataForAsset

For video: requestExportSessionForVideo

+6
source

The following code helped me. It is 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") } }) 
+2
source

All Articles