大文件下载
1 @interface ViewController () { 2 // 文件的总长度 3 int _totalLength; 4 } 5 @property (nonatomic, retain) NSMutableData *data; 6 @end 7 8 @implementation ViewController 9 - (void)dealloc { 10 [_data release]; 11 [super dealloc]; 12 } 13 14 - (void)viewDidUnload { 15 [super viewDidUnload]; 16 self.data = nil; 17 } 18 19 - (void)viewDidLoad 20 { 21 [super viewDidLoad]; 22 // Do any additional setup after loading the view, typically from a nib. 23 24 25 } 26 27 - (void)download { 28 29 self.data = [NSMutableData data]; 30 31 NSURL *url = [NSURL URLWithString:@"http://192.168.1.106:8080/Server/movie.avi"]; 32 33 NSURLRequest *reuqest = [NSURLRequest requestWithURL:url]; 34 35 [[NSURLConnection connectionWithRequest:reuqest delegate:self] start]; 36 } 37 38 #pragma mark - 代理方法 39 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 40 [self.data appendData:data]; 41 42 // 设置下载进度 43 self.progressView.progress = (float)self.data.length / (float)_totalLength; 44 } 45 46 #pragma mark 服务器有相应就会调用这个方法 47 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 48 NSHTTPURLResponse *rep = (NSHTTPURLResponse *)response; 49 50 _totalLength = [[[rep allHeaderFields] objectForKey:@"Content-Length"] intValue]; 51 } 52 53 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { 54 NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 55 56 NSString *dir = [cacheDir stringByAppendingPathComponent:@"movie"]; 57 58 NSFileManager *mgr = [NSFileManager defaultManager]; 59 60 // 是否为文件夹 61 BOOL isDir; 62 // 是否存在 63 BOOL exist = [mgr fileExistsAtPath:dir isDirectory:&isDir]; 64 if (!exist) { 65 // 创建一个新的文件夹 66 [mgr createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil]; 67 } 68 69 NSString *path = [dir stringByAppendingPathComponent:@"mj.avi"]; 70 // 将文件数据写入Library/Caches文件夹下 71 [self.data writeToFile:path atomically:YES]; 72 } 73 @end