NSURLSession下載和斷點續傳,nsurlsession

來源:互聯網
上載者:User

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;    }) ;}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.