I have some URLs for the videos stored in camera rolls. For example:
file:///var/mobile/Media/DCIM/100APPLE/IMG_0249.MP4
I would like to further process those videos as NSData, but if I use
NSURL* videoURL = [NSURL fileURLWithPath:@"file:///var/mobile/Media/DCIM/100APPLE/IMG_0249.MP4"];
NSData *imageData = [NSData dataWithContentsOfURL:videoURL options:NSDataReadingMappedIfSafe error:&error];
The data is always nil. And I get the following error:
Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_0249.MP4” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0249.MP4, NSUnderlyingError=0x165351d0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
I noticed that if the URL is from my local app document folder, I can generate NSData without any issues. I wonder if it's not allowed to create NSData out of the videos stored in Camera Roll. I wonder if I need to use the Photos framework or some other method in order to have the permission.
It turns out that I can't turn a URL for Camera Rolls videos into NSData directly, I need to use PHImageManager to do that (And use the localIdentifier of the PHAsset of the video I acquired in the past):
PHFetchResult* assets = [PHAsset fetchAssetsWithLocalIdentifiers:@[videoID] options:nil];
PHAsset *asset = assets.firstObject;
if (asset.mediaType == PHAssetMediaTypeVideo) {
[[PHImageManager defaultManager] requestAVAssetForVideo:asset options:nil resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
if ([asset isKindOfClass:[AVURLAsset class]]) {
AVURLAsset* urlAsset = (AVURLAsset*)asset;
NSData *data = [NSData dataWithContentsOfURL:urlAsset.URL];
[self sendToTwitter:data withMessage:message account: account];
}
}];
}
My guess is that the AVURLAsset* urlAsset has some additional permission info that my previous approach through [NSURL fileURLWithPath] doesn't have.