iOS中下載大型文件,需要考慮到占用內存的大小與下載速度(使用多線程),因此本文首先介紹一個原理性下載文件的DEMO。
在下載大型文件中,需要知道下載的進度因此需要使用代理模式,不斷的回調下載進度。
- (void)downLoad {
// 1.URL
NSURL *url = [NSURL URLWithString:@”http://localhost:8080/MJServer/resources/videos.zip“];
// 2.NURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.開始創建TCP連接
[NSURLConnection connectionWithRequest:request delegate:self];
// [[NSURLConnection alloc]initWithRequest:request delegate:self];
// NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
// [connection start];
}
下面是代理方法:
- (void)connection:(NSURLConnection )connection didFailWithError:(NSError )error {
NSLog(@”didFailWithError”);
}
- (void)connection:(NSURLConnection )connection didReceiveResponse:(NSURLResponse )response {
self.fileData = [NSMutableData data];
// NSHTTPURLResponse * resp = (NSHTTPURLResponse*)response;
// long long fileLength = [resp.allHeaderFields[@”Content-Length”]longLongValue];
self.totalLength = response.expectedContentLength;
}
- (void)connection:(NSURLConnection )connection didReceiveData:(NSData )data {
[self.fileData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [caches stringByAppendingPathComponent:@”videos.zip”];
[self.fileData writeToFile:file atomically:YES];
}
設計的總思路:
(1)創建NSURLConnection的對象,并建立網絡下載
(2)根據代理方法來回調報告下載數據以及進度
(3)不斷的累計下載data
(4)最后將下載的數據寫入到沙盒緩存中
注意這里的回調方法都是在主線程中執行的.