您的位置:首页 > 其它

如何下载一个视频文件到Documents目录下的Video文件夹

2015-12-26 17:30 791 查看
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

//获取程序根目录
//    NSString *rootPath = NSHomeDirectory();

//获取程序根目录下得Ducuments
//   NSString *documentsPath = [rootPath stringByAppendingFormat:@"/%@",@"Documents"];
//或者
//    documentsPath = [rootPath stringByAppendingPathComponent:@"Documents"];
//    常用的获取Documents目录方法
//   NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES)objectAtIndex:0];
//    NSLog(@"documentsPath = %@",documentsPath);

//下载一个视频文件到Documents目录下得Video文件夹
NSString *videoPath = [self creatDirInDocuments:@"Video"];
NSLog(@"videoPath = %@",videoPath);
if (videoPath !=nil)
{
NSFileManager *fileManage = [NSFileManager defaultManager];
NSString *videoUrlString = @"http://v8.tv.cctv5.cctv.com/r5wbth/4d/e7/4de76971-63f4-4717-f28b-03d757a7704f/mp4h.mp4";
NSRange range = [[videoUrlString lastPathComponent]rangeOfString:@".mp4"];//
NSString *videoUrlStirngNew = [[videoUrlString lastPathComponent]substringFromIndex:range.location+4];
NSString *fileVideo = [videoPath stringByAppendingPathComponent:videoUrlStirngNew];
//如果文件夹不存在该路径
if (![fileManage fileExistsAtPath:fileVideo])
{
//进行编码
//            videoUrlString = [videoUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSCharacterSet *characterSet = [NSCharacterSet URLQueryAllowedCharacterSet];
videoUrlString = [videoUrlString stringByAddingPercentEncodingWithAllowedCharacters:characterSet];
//我们的图片 视频 音频等在网络中都是以二进制文件传输,所以我们这里拿到的是data
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:videoUrlString]];
if (data == nil)
{
NSLog(@"网络出错,请稍后再试");
}
else
{
//用单例类  NSFileManager的对象,将文件写入本地
BOOL isSuccess = [fileManage createFileAtPath:fileVideo contents:data attributes:nil];
if (isSuccess)
{
NSLog(@"视频下载成功");
}
else
{
NSLog(@"视频下载失败");
}

}
}

}

}
//第一步封装
//这里我们封装一个函数,使得这个函数返回的是我们在Documents目录下想要的文件夹的路径
-(NSString *)creatDirInDocuments:(NSString *)dirName
{
//获得Documents的文件路径
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
//拼接成我们想要的文件的路径的字符串
NSString *dirDocuments = [documentsPath stringByAppendingPathComponent:dirName];
//获取NSFileManager 单例类,用文件操作
NSFileManager *fileManager = [NSFileManager defaultManager];
//判断是否存在某个文件或文件夹
BOOL isExist = [fileManager fileExistsAtPath:dirDocuments];
if (!isExist)
{
//创建文件夹
NSError *error;
BOOL isSuccess = [fileManager createDirectoryAtPath:dirDocuments withIntermediateDirectories:YES attributes:nil error:&error];
if (!isSuccess)
{
//如果文件夹创建失败,将打印错误信息
NSLog(@"error = %@",error.debugDescription);
dirDocuments = nil;
}
}

return dirDocuments;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: