Search code examples
iosxcodensdataphasset

Get NSData for video file with NSUrl


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.


Solution

  • 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.