标签:
---恢复内容开始---
1.要了解NSFileHandle的用法,注意下载完要关闭这个对象。还要记得每次写入之前将它的文件指针挪位!
// // ViewController.m // 多值参数 // // Created by Mac on 16/1/23. // Copyright © 2016年 Mac. All rights reserved. // #define ZZFile [ [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"minion_15.mp4"] #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> @property (weak, nonatomic) IBOutlet UIProgressView *proView; //@property (nonatomic, strong) NSMutableData *fileData; @property (nonatomic, assign) NSInteger contentLength; @property (nonatomic, assign) NSInteger currentLength; @property (nonatomic, strong) NSFileHandle *handle; //@property (nonatomic, strong) UIImage *image; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 这种方法没法暂停,只适合下载小文件 NSURL *url = [[NSURL alloc] initWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4" ]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; // 设置connect的代理 [NSURLConnection connectionWithRequest:request delegate:self]; } #pragma mark - NSURLConnect 的代理 // connection接收到响应,此时应当创建数据准备拼接data - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { NSHTTPURLResponse *newResponse = response; // 获得文件的总长度 self.contentLength = [newResponse.allHeaderFields[@"Content-Length"] integerValue]; // 创建一个空的文件 [[NSFileManager defaultManager] createFileAtPath:ZZFile contents:nil attributes:nil]; self.handle = [NSFileHandle fileHandleForWritingAtPath:ZZFile]; } // 接收到了数据,这个方法会被多次调用,需要在这里拼接数据 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // 接收到数据后写入文件 // 设置当前下载量 self.currentLength += data.length; // 制定文件的写入位置,在当前文件的最后面 [self.handle seekToEndOfFile]; // 写入数据 [self.handle writeData:data]; self.proView.progress = 1.0 * self.currentLength / self.contentLength; } // 下载完成 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // 下载完毕后需要关闭handle [self.handle closeFile]; self.handle = nil; self.currentLength = 0; } @end
标签:
原文地址:http://www.cnblogs.com/BJTUzhengli/p/5154478.html