简单地视频下载实现, 包含进度条.
@interface DownloadViewController ()<NSURLConnectionDataDelegate>
@property (strong, nonatomic) UIProgressView *progress;
@property (strong, nonatomic) NSFileHandle *writeHandle;
@property (assign, nonatomic) long long currentLength;
@property (assign, nonatomic) long long sumLength;
@end
@implementation DownloadViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
}
return self;
}
- (UIProgressView *)progress{
if (!_progress) {
_progress = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
_progress.backgroundColor = [UIColor redColor];
_progress.frame = CGRectMake(30, 100, self.view.frame.size.height - 100, 20);
_progress.progressTintColor = [UIColor whiteColor];
_progress.trackTintColor = [UIColor blackColor];
_progress.progress = 0;
}
return _progress;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor greenColor];
[self.view addSubview:self.progress];
[self createConnection];
}
- (void) createConnection{
NSURL *url = [NSURL URLWithString:@"http://vmovier.qiniudn.com/eea389000bc9187034f99788df6d13e6.mp4"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [cache stringByAppendingPathComponent:@"man.mp4"];
NSLog(@"%@", filePath);
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:filePath contents:nil attributes:nil];
// 创建写数据的文件句柄
self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
// 获取完整的长度
self.sumLength = response.expectedContentLength;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
self.currentLength += data.length;
self.progress.progress = (double)self.currentLength / self.sumLength;
NSLog(@"接收到的数据! ------ %ld", data.length);
[self.writeHandle seekToEndOfFile];
[self.writeHandle writeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"下载完毕");
// 关闭连接, 不再输入数据在文件中
[self.writeHandle closeFile];
// 销毁
self.writeHandle = nil;
// 在下载完毕后, 对进度进行清空
self.currentLength = 0;
self.sumLength = 0;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"error = %@", error);
}
在读取的时候只要使用NSURL的fileURLWithPath方法就可以啦.
NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *path= [NSString stringWithFormat:@"%@/man.mp4", cache];
NSURL *url = [NSURL fileURLWithPath:path];