简体   繁体   中英

How to convert mp4 to NSData?

在此处输入图像描述I have file in XCode with name vvideo.mp4. I am trying to convert it to NSData like below

    NSData *data = [NSData dataWithContentsOfFile:@"vvideo.mp4" options:nil error:nil];

But as I log data, it returns null.

What is right way to convert any video to NSData?

File is added and copies properly in Xcode, you can see here.

EDITED QUESTION....

dataWithContentsOfFile:options:error: takes a file path and not file name. If the video file is in application bundle you should do,

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"vvideo" ofType:@"mp4"];

NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:filePath options:nil error:&error];
if(data == nil && error!=nil) {
    //Print error description
}

Rather than passing error argument as nil pass the value, it will be useful in understanding error condition, if any occurs.

Hope that helps!

This is how you can do this in Swift 5:

if let path = Bundle.main.path(forResource: "download", ofType: "mp4"),
   let data = try? Data.init(contentsOf: URL(fileURLWithPath: path)) {
      // Use this data
}

Very important thing to note here is that the file has to be somewhere inside the project instead of Assets.xcassets otherwise path would be nil .

Also make sure to associate the correct Target Membership for example:

在此处输入图像描述

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM