NSURLConnection實現(xiàn)大文件斷點下載:主要通過設(shè)置請求頭告訴服務(wù)器要下載視頻某一部分,以及句柄寡具。
#import"ViewController.h"
@interfaceViewController()
@property(weak,nonatomic)IBOutletUIProgressView*progressView;
@property(nonatomic,assign)NSIntegertotalSize;
@property(nonatomic,assign)NSIntegercurrentSize;
/**文件句柄*/
@property(nonatomic,strong)NSFileHandle*handle;
/**沙盒路徑*/
@property(nonatomic,strong)NSString*fullPath;
/**連接對象*/
@property(nonatomic,strong)NSURLConnection*connect;
@end
@implementationViewController
- (IBAction)startBtnClick:(id)sender {
[selfdownload];
}
- (IBAction)cancelBtnClick:(id)sender {
[self.connectcancel];
}
- (IBAction)goOnBtnClick:(id)sender {
[selfdownload];
}
//內(nèi)存飆升
-(void)download
{
//1.url
NSURL*url = [NSURLURLWithString:@"http://www.33lc.com/article/UploadPic/2012-10/2012102514201759594.jpg"];
//2.創(chuàng)建請求對象
NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url];
//設(shè)置請求頭信息,告訴服務(wù)器值請求一部分?jǐn)?shù)據(jù)range
/*
bytes=0-100
bytes=-100 最后100個字節(jié)
bytes=100-請求100之后的所有數(shù)據(jù)
*/
NSString*range = [NSStringstringWithFormat:@"bytes=%zd-",self.currentSize];
[requestsetValue:rangeforHTTPHeaderField:@"Range"];
NSLog(@"+++++++%@",range);
//3.發(fā)送請求
NSURLConnection*connect = [[NSURLConnectionalloc]initWithRequest:requestdelegate:self];
self.connect= connect;
}
#pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
NSLog(@"didReceiveResponse");
//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:@"123.jpg"];
NSLog(@"%@",self.fullPath);
//3.創(chuàng)建一個空的文件
[[NSFileManagerdefaultManager]createFileAtPath:self.fullPathcontents:nilattributes:nil];
//NSDictionary *dict = [[NSFileManager defaultManager]attributesOfItemAtPath:self.fullPath error:nil];
//4.創(chuàng)建文件句柄(指針)
self.handle= [NSFileHandlefileHandleForWritingAtPath:self.fullPath];
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
//1.移動文件句柄到數(shù)據(jù)的末尾
[self.handleseekToEndOfFile];
//2.寫數(shù)據(jù)
[self.handlewriteData: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;
//NSLog(@"%@",self.fullPath);
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
//1.關(guān)閉文件句柄
[self.handlecloseFile];
self.handle=nil;
NSLog(@"connectionDidFinishLoading");
NSLog(@"%@",self.fullPath);
}
@end