国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

NSURLSession下載和斷點續傳

2019-11-14 19:09:42
字體:
來源:轉載
供稿:網友

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

 

作者:杰瑞教育
出處:http://www.survivalescaperooms.com/jerehedu/ 
本文版權歸煙臺杰瑞教育科技有限公司和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 浮山县| 桐柏县| 芦溪县| 新郑市| 宕昌县| 全椒县| 南陵县| 鞍山市| 山西省| 清新县| 外汇| 商河县| 昭通市| 龙胜| 翼城县| 乌鲁木齐市| 威远县| 金堂县| 洞口县| 原阳县| 宁安市| 温泉县| 石门县| 阳高县| 海阳市| 平遥县| 张家港市| 周至县| 扎鲁特旗| 天峻县| 大城县| 荔浦县| 锦屏县| 定安县| 广宁县| 邳州市| 平江县| 东阿县| 福泉市| 黑水县| 永寿县|