NSURLSession下載和斷點續傳,nsurlsession
NSURLSession是iOS7之後新的網路介面,和經常用到NSURLConnection是類似的。在程式在前台時,NSURLSession與NSURLConnection可以相互的替代。但是當使用者在對程式進行強制關閉的時候此時NSURLSession會預設的自動斷開。相比而言NSURLSession的優勢主要體現在後台操作時候,而且在最流行的架構AFNetworking中也對NSURLSession提供了更好的支援。
主要提供的功能如下:
1 下載檔案到記憶體中
2 下載檔案到路徑
3 上傳制定的檔案等
案例示範:圖片下載斷點續傳
主要代碼:
1、定義幾個全域變數
@interface ViewController (){ NSURLSessionDownloadTask * _task; NSData * _data; NSURLSession * _session; NSURLRequest * _request; UIProgressView * _pro; UIImageView * _imageView; }
2、向視圖中添加圖片進度條
_imageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)]; _imageView.center=self.view.center; [self.view addSubview:_imageView]; _pro=[[UIProgressView alloc] initWithFrame:CGRectMake(_imageView.frame.origin.x, _imageView.frame.origin.y+400, 300, 40)];
3、向視圖中添加按鈕(同樣的方式添加三個)
UIButton * button=[[UIButton alloc] initWithFrame:CGRectMake(50, _imageView.frame.origin.y+400+20, 50, 40)]; button.backgroundColor=[UIColor blueColor]; [button setTitle:@"開始" forState:UIControlStateNormal]; [button addTarget:self action:@selector(ddLoad) forControlEvents:UIControlEventTouchUpInside]; button.layer.borderWidth=1; button.layer.borderColor=[UIColor blueColor].CGColor; button.layer.cornerRadius=5; [self.view addSubview:button];
4、通過AFNetworkReachabilityManager網路狀態監測
- (void) _checkNet{ //開啟網路狀態監控 [[AFNetworkReachabilityManager sharedManager] startMonitoring]; [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { if(status==AFNetworkReachabilityStatusReachableViaWiFi){ NSLog(@"當前是wifi"); } if(status==AFNetworkReachabilityStatusReachableViaWWAN){ NSLog(@"當前是3G"); }if(status==AFNetworkReachabilityStatusNotReachable){ NSLog(@"當前是沒有網路"); }if(status==AFNetworkReachabilityStatusUnknown){ NSLog(@"當前是未知網路"); } }];}
5、開始下載
- (void) ddLoad{ NSURLSessionConfiguration * config=[NSURLSessionConfiguration defaultSessionConfiguration]; _session=[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; // NSURL *url=[NSURL URLWithString:@src]; _request=[NSURLRequest requestWithURL:url]; _task= [_session downloadTaskWithRequest:_request]; NSLog(@"開始載入"); [_task resume];}
6、設定暫停和回複
- (void) pause{ //暫停 NSLog(@"暫停下載"); [_task cancelByProducingResumeData:^(NSData *resumeData) { _data=resumeData; }]; _task=nil;}- (void) resume{ //恢複 NSLog(@"恢複下載"); if(!_data){ NSURL *url=[NSURL URLWithString:@src]; _request=[NSURLRequest requestWithURL:url]; _task=[_session downloadTaskWithRequest:_request]; }else{ _task=[_session downloadTaskWithResumeData:_data]; } [_task resume]; }
7、代理方法儲存下載檔案監控下載進度
#pragma mark - delegate- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ NSURL * url=[NSURL fileURLWithPath:@"/Users/jredu/Desktop/tt.png"]; NSFileManager * manager=[NSFileManager defaultManager]; [manager moveItemAtURL:location toURL:url error:nil]; dispatch_async(dispatch_get_main_queue(), ^{ NSData * data=[manager contentsAtPath:@"/Users/jredu/Desktop/tt.png"]; UIImage * image=[[UIImage alloc ]initWithData:data]; _imageView.image=image; UIAlertView * alert=[[UIAlertView alloc] initWithTitle:nil message:@"下載完成" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alert show]; }) ;}- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWrittentotalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ CGFloat progress=(totalBytesWritten*1.0)/totalBytesExpectedToWrite; dispatch_async(dispatch_get_main_queue(), ^{ _pro.progress=progress; }) ;}