大文件下載分析
在大文件的下載時,文件的下載傳輸時間較長,需要使用到暫停或者下載中意外退出時候仍能繼續(xù)上次的下載進度.
使用的類
-
NSURLConnction
的代理方法寫入沙盒中 - 使用文件句柄(指針)
NSFileHandle
在接受數(shù)據(jù)每次將句柄移動到數(shù)據(jù)末尾seekToEndOfFile
使用句柄寫數(shù)據(jù); - 在
NSMutableURLRequest
請求頭中設(shè)定Range,實現(xiàn)斷點下載; - 使用
NSFileManager
來獲取文件的大小;
實現(xiàn)代碼
- 設(shè)置相關(guān)的屬性
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/**目標(biāo)文件小大*/
@property (nonatomic, assign) NSInteger totalSize;
/**當(dāng)前已下載的文件小大*/
@property (nonatomic, assign) NSInteger currentSize;
/** 文件句柄*/
@property (nonatomic, strong)NSFileHandle *handle;
/** 沙盒路徑 */
@property (nonatomic, strong) NSString *fullPath;
/** 連接對象 */
@property (nonatomic, strong) NSURLConnection *connect;
- 建立請求對象
在請求頭里面設(shè)置要請求的文件起始位置,實現(xiàn)斷點下載,避免重復(fù)重復(fù)請求資源
NSURL *url = [NSURL URLWithString:@"下載資源的地址"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//設(shè)置請求頭信息,告訴服務(wù)器值請求一部分數(shù)據(jù)range
/*
bytes=0-100
bytes=-100
bytes=0- 請求100之后的所有數(shù)據(jù)
*/
NSString *range = [NSString stringWithFormat:@"bytes=%zd-",self.currentSize];
[request setValue:range forHTTPHeaderField:@"Range"];
//發(fā)送請求
self.connect = [[NSURLConnection alloc]initWithRequest:request delegate:self];
- 實現(xiàn)代理方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//1.得到文件的總大小(本次請求的文件數(shù)據(jù)的總大小 != 文件的總大小)
// self.totalSize = response.expectedContentLength + self.currentSize;
if (self.currentSize >0) {
return;
}
self.totalSize = response.expectedContentLength;
//2.寫數(shù)據(jù)到沙盒中
self.fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"文件路徑"];
NSLog(@"%@",self.fullPath);
//3.創(chuàng)建一個空的文件
[[NSFileManager defaultManager] createFileAtPath:self.fullPath contents:nil attributes:nil];
//NSDictionary *dict = [[NSFileManager defaultManager]attributesOfItemAtPath:self.fullPath error:nil];
//4.創(chuàng)建文件句柄(指針)
self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullPath];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//1.移動文件句柄到數(shù)據(jù)的末尾
[self.handle seekToEndOfFile];
//2.寫數(shù)據(jù)
[self.handle writeData:data];
//3.獲得進度
self.currentSize += data.length;
//進度=已經(jīng)下載/文件的總大小
NSLog(@"%f",1.0 * self.currentSize/self.totalSize);
self.progressView.progress = 1.0 * self.currentSize/self.totalSize;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//此處注意要關(guān)閉文件句柄
[self.handle closeFile];
self.handle = nil;
}
取消或繼續(xù)下載
/**取消任務(wù)還不可逆的*/
[self.connect cancel];