Get NSData for video file with NSUrl

982 views Asked by At

I have file at path

var/mobile/Media/DCIM/100APPLE/IMG_0292.MOV

and I want to get NSData of this file but I got error

Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_0292.MOV” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0292.MOV, NSUnderlyingError=0x178c9f90 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

I tried with

NSError *error;
NSData *videoData = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedAlways error:&error];

and

NSError* error = nil;
NSData* data = [NSData dataWithContentsOfURL:fileURL options:NSDataReadingUncached error:&error];

and no luck.

I also have PHAsset of video file but don't know how to get NSData from it. Please help me get NSData.

2

There are 2 answers

0
holtmann On BEST ANSWER

You can not access URLs directly that are not within your apps sandbox (without a few exceptions). To get the data for a video file, please take a look at the following methods:

For iOS 9 or higher use the following method of PHAssetResource:

- (PHAssetResourceDataRequestID)requestDataForAssetResource:(PHAssetResource *)resource options:(PHAssetResourceRequestOptions *)options dataReceivedHandler:(void (^)(NSData *data))handlercompletionHandler:(void (^)(NSError *error))completionHandler;

For iOS 8 or higher:

- (PHImageRequestID)requestExportSessionForVideo:(PHAsset *)asset options:(PHVideoRequestOptions *)options exportPreset:(NSString *)exportPreset resultHandler:(void (^)(AVAssetExportSession *exportSession, NSDictionary *info))resultHandler;

Then read the NSData of the exported URL.

0
amcastror On

Just for completion sake.. This worked for me:

    PHImageManager *manager = [PHImageManager defaultManager];
    [manager requestAVAssetForVideo:asset.baseAsset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {

        if([asset isKindOfClass:[AVURLAsset class]]){
             //Get the url 
             NSURL *url = [(AVURLAsset *)asset URL];
        }

    }];

Hope this helps.