How to get NSData from file by using PHAsset

Dmitry Nelepov picture Dmitry Nelepov · Feb 26, 2016 · Viewed 9.1k times · Source

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.

Answer

holtmann picture holtmann · Mar 1, 2016

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