NSURLSession的简单使用

本文详细介绍了NSURLSession的异步请求方式,并对比了与NSURLConnection的不同之处。主要讲解了NSURLSessionDataTaskDelegate及NSURLDownloadDelegate的使用方法,包括如何设置代理、执行请求、处理数据接收及错误情况等。

NSURLSession的简单使用(不同于NSURLConnection,仅仅支持异步请求)

dataTask,简单请求直接block里面执行,不走代理

NSURLSessionDataTaskDelegate:

签订代理:

-NSURLConfiguration *configuration = [NSURLConfiguration defaultConfiguration]

-NSURLSession *session = [NSURLSession sessionWithConfiguration:delegate:queue:nil]

实现相应的代理方法:

-didRecieveResponse

completionHander(…)

三种类型:

NSURLSessionResponseCancer = 0;默认,取消任务

NSURLSessionResponseAllow = 1;任务继续执行

NSURLSessionResponseBecomeDownload = 2;dataTask变为downloadTask

根据response,拿到数据长度

1.将response转为NSHTTPURLResponse

2.获取响应头 NSDictionary *header = [httpResponse allHeaders];

3.获取长度 CGFloat length = [header[@“Content-Length”] longlongValue];

-didReceiveData

收到data,举个例子,图片的渐进式加载

1.[gData appendData];

2.根据现有data更新imageSouceRef

CGImageSourceUpdate(container,data,final:YES|NO);

3.创建CGImageRef

CGImageSourceCreateAtIndex(container,0,option:null);

4.创建image

UIImage *curImage = [UIImage imageWithCGImage:imageRef];

5.释放imageRef

CGImageRelease(imageRef);

-didCompleteWithError

任务完成后的相关处理

 

NSURLDownloadDelegate

代理方法:

-didWriteData

totalBytesWritten:当前写入的data

totalBytesExpectedToWritten:总计要写入的data

-didResumeAtOffset

fileOffset:已经写入的流

expectedTotalBytes:全部数据

task的三种状态:

resume,suspend,cancer

-didFinishDownloadingToUrl

location:临时的存储路径,使用fileManager移位

1.创建路径 NSString *path  = [NSSearchDirectoryInDomain(NSCacheDirectory,NSUserDomainMask,YES) lastObject] stringByAppendingPathComponent:@“filename.type”];

2.移位 [NSFileManager default] moveItemAtPath:location.path toPath:path error:]

根据location拿到data

NSData *data = [NSData dataWithContentsOfUrl:location];

-didCompleteWithError

转载于:https://www.cnblogs.com/xiaoerheiwatu/p/6723585.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值