iOS下载大文件原理解析一
iOS中下載大型文件,需要考慮到占用內(nèi)存的大小與下載速度(使用多線程),因此本文首先介紹一個原理性下載文件的DEMO。
在下載大型文件中,需要知道下載的進度因此需要使用代理模式,不斷的回調(diào)下載進度。
- (void)downLoad {
// 1.URL
NSURL *url = [NSURL URLWithString:@”http://localhost:8080/MJServer/resources/videos.zip“];
// 2.NURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.開始創(chuàng)建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];
}
設(shè)計的總思路:
(1)創(chuàng)建NSURLConnection的對象,并建立網(wǎng)絡(luò)下載
(2)根據(jù)代理方法來回調(diào)報告下載數(shù)據(jù)以及進度
(3)不斷的累計下載data
(4)最后將下載的數(shù)據(jù)寫入到沙盒緩存中
注意這里的回調(diào)方法都是在主線程中執(zhí)行的.
總結(jié)
以上是生活随笔為你收集整理的iOS下载大文件原理解析一的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 淘宝弹性布局方案lib-flexible
- 下一篇: 如何用JS和HTML 做一个桌面炒股小插