美文网首页
把NSData 保存到本地!

把NSData 保存到本地!

作者: sdr小米 | 来源:发表于2017-07-28 00:03 被阅读0次

    1.获取Caches 文件夹路径。

    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSLog:    /Users/sundongri/Library/Developer/CoreSimulator/Devices/649D1D25-FA3F-4EB2-96FC-92AF6A6B9D97/data/Containers/Data/Application/5668FC61-F42D-4C07-9761-24577C5327CE/Library/Caches

    2.在Caches 文件夹下面 建一个子文件夹便于管理!

    NSString *imagePath = [NSString stringWithFormat:@"%@/Media", pathDocuments];

    [[NSFileManager defaultManager] createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];

    NSLog:  /Users/sundongri/Library/Developer/CoreSimulator/Devices/649D1D25-FA3F-4EB2-96FC-92AF6A6B9D97/data/Containers/Data/Application/5668FC61-F42D-4C07-9761-24577C5327CE/Library/Caches/Media

    文件名字为Media。

    3.获取NSData

    //工程里的视频

    NSString * path = [[NSBundle mainBundle] pathForResource:@"D0024" ofType:@"mp4"];

    //转化成NSData

    NSData *videoMy=[NSData dataWithContentsOfFile:path];

    //初始化一个动态的data 容器 

    NSMutableData *videoData =[NSMutableData data];

    //初始化要用这种  不要用videoData=nil;

    [videoData setData:[NSData data]];

    //添加Data 也可以用来接收下载过来的Data,因为下载的数据是一段一段过来的 所以appendData 不断的加(本地的数据就一次行加进来了)

    [videoData appendData:videoMy];

    //imagePath 是咱们创建的media文件夹拼上DJI_0024.mp4 ,最后结尾为media/DJI_0024.mp4

    NSString *filePath = [imagePath stringByAppendingPathComponent:@"DJI_0024.mp4"];

    //接下来就是写进文件 然后播放本地文件

    BOOL isSuccess = [videoData writeToFile:filePath atomically:YES];

    if (isSuccess) {

    NSLog(@"能写进去");

    }

    else{

    NSLog(@"不成功");

    }

    NSURL *url = [NSURL fileURLWithPath:filePath];

    AVPlayerViewController * play = [[AVPlayerViewController alloc]init];

    play.player = [[AVPlayer alloc]initWithURL:url];

    [self presentViewController:play animated:YES completion:nil];

    PS:下载视频的时候如果要算下载进度,如果(总字节)fileSizeInBytes/1048576 后面加个M 就是一共有多少兆了!!

    相关文章

      网友评论

          本文标题:把NSData 保存到本地!

          本文链接:https://www.haomeiwen.com/subject/ocatlxtx.html