Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get NSData from file by using PHAsset

I have file at 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 got nothing but error:

Error Domain=NSCocoaErrorDomain Code=257 "Не удалось завершить операцию. (Cocoa, ошибка 257)" UserInfo=0x175a61380 {NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0197.mov, NSUnderlyingError=0x17424e550 "Не удалось завершить операцию. Operation not permitted"}

File exists but I can't read it.

But at the same time AVPlayer normally plays video file.

I tried

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

But I did not get any result.

like image 606
Dmitry Nelepov Avatar asked Dec 14 '22 08:12

Dmitry Nelepov


2 Answers

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

like image 160
holtmann Avatar answered Dec 21 '22 13:12

holtmann


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")
                    }
                })
like image 22
Mobile Developer Avatar answered Dec 21 '22 15:12

Mobile Developer