NSURLSession的简单使用

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