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、向視圖中添加按鈕(一樣的方式添加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)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ CGFloat progress=(totalBytesWritten*1.0)/totalBytesExpectedToWrite; dispatch_async(dispatch_get_main_queue(), ^{ _pro.progress=progress; }) ; }
上一篇 Div 內容垂直居中
下一篇 匯編-條件跳轉與重復指令