iOS網絡編程(六)

NSURLConnection實現大文件斷點下載:主要通過設置請求頭告訴服務器要下載視頻某一部分,以及句柄。

#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];

}

//內存飆升

-(void)download

{

//1.url

NSURL*url = [NSURLURLWithString:@"http://www.33lc.com/article/UploadPic/2012-10/2012102514201759594.jpg"];

//2.創建請求對象

NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url];

//設置請求頭信息,告訴服務器值請求一部分數據range

/*

bytes=0-100

bytes=-100 最后100個字節

bytes=100-請求100之后的所有數據

*/

NSString*range = [NSStringstringWithFormat:@"bytes=%zd-",self.currentSize];

[requestsetValue:rangeforHTTPHeaderField:@"Range"];

NSLog(@"+++++++%@",range);

//3.發送請求

NSURLConnection*connect = [[NSURLConnectionalloc]initWithRequest:requestdelegate:self];

self.connect= connect;

}

#pragma mark ----------------------

#pragma mark NSURLConnectionDataDelegate

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response

{

NSLog(@"didReceiveResponse");

//1.得到文件的總大小(本次請求的文件數據的總大小!=文件的總大小)

// self.totalSize = response.expectedContentLength + self.currentSize;

if(self.currentSize>0) {

return;

}

self.totalSize= response.expectedContentLength;

//2.寫數據到沙盒中

self.fullPath= [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject]stringByAppendingPathComponent:@"123.jpg"];

NSLog(@"%@",self.fullPath);

//3.創建一個空的文件

[[NSFileManagerdefaultManager]createFileAtPath:self.fullPathcontents:nilattributes:nil];

//NSDictionary *dict = [[NSFileManager defaultManager]attributesOfItemAtPath:self.fullPath error:nil];

//4.創建文件句柄(指針)

self.handle= [NSFileHandlefileHandleForWritingAtPath:self.fullPath];

}

-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data

{

//1.移動文件句柄到數據的末尾

[self.handleseekToEndOfFile];

//2.寫數據

[self.handlewriteData:data];

//3.獲得進度

self.currentSize+= data.length;

//進度=已經下載/文件的總大小

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.關閉文件句柄

[self.handlecloseFile];

self.handle=nil;

NSLog(@"connectionDidFinishLoading");

NSLog(@"%@",self.fullPath);

}

@end

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容