NSURLSession 学习笔记

时间:2021-04-13 09:52:54

NSURLSession 学习笔记

一:NSURLSession

  • 类似之前的NSURLConnection, 可配置每个session的 cookie,证书等网络连接配置信息

    NSURLSessionConfiguration

  • 包含三大任务 :NSURLSessionTask--(NSURLSessionDataTask,NSURLSessionUploadTask,NSURLSessionDownloadTask)
  • 常用api
@interface NSURLSession : NSObject

// 单例
+ (NSURLSession *)sharedSession; //配置 Session
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration;
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(id <NSURLSessionDelegate>)delegate delegateQueue:(NSOperationQueue *)queue;
/*Data 请求 request */
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request; /* Data 请求 url. */
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url; /* 上传文件请求 fileUrl */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL; /* 上传Data请求 NSData */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData; /* 上传数据流请求 request */
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request; /* 下载文件.request */
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request; /* 下载文件 url */
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url; /* 断点下载请求 , */
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;

异步请求操作

@interface NSURLSession (NSURLSessionAsynchronousConvenience)
/* 异步数据请求 NSData */
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler; /*
* 异步文件上传请求 file,NSData
*/
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler; /* 异步下载请求 */
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler; @end

二:NSURLSessionTask 任务

  • 包含三大任务 :NSURLSessionTask--(NSURLSessionDataTask,NSURLSessionUploadTask,NSURLSessionDownloadTask)
  • 关系图

NSURLSession 学习笔记

系统定义的 常用api,如,对 网络任务的暂停,继续

@interface NSURLSessionTask : NSObject <NSCopying>

  ........

/* 取消任务*/
- (void)cancel; /* 任务状态*/
@property (readonly) NSURLSessionTaskState state; /*任务暂停和继续 */
- (void)suspend;
- (void)resume;
........
@end

任务状态:

typedef NS_ENUM(NSInteger, NSURLSessionTaskState) {
NSURLSessionTaskStateRunning = , /* The task is currently being serviced by the session */
NSURLSessionTaskStateSuspended = ,
NSURLSessionTaskStateCanceling = , /* The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError: message. */
NSURLSessionTaskStateCompleted = , /* The task has completed and the session will receive no more delegate notifications */
} NS_ENUM_AVAILABLE(10_9, 7_0);

三大子类,Data,Upload,Download操作 ,都是抽象类,基本不提供任何操作

@interface NSURLSessionDataTask : NSURLSessionTask
@end /*
* An NSURLSessionUploadTask does not currently provide any additional*/ @interface NSURLSessionUploadTask : NSURLSessionDataTask
@end @interface NSURLSessionDownloadTask : NSURLSessionTask /*断点续传 */
- (void)cancelByProducingResumeData:(void (^)(NSData *resumeData))completionHandler; @end

三:演示代码

1:异步的GET 请求 Data 数据

    NSURL *url = [NSURL URLWithString:@"http://httpbin.org/get"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]); }]; //任务创建后,不会立即执行,调用resume 立即执行;
[dataTask resume];

2:异步 下载文件

    NSURL *url = [NSURL URLWithString:@"http://dl.360safe.com/360zip_setup_3.1.0.2061.exe"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *downTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) { //文件下载会被先写入到一个 临时路径 location,我们需要将下载的文件移动到我们需要地方保存
NSURL *savePath = [NSURL fileURLWithPath:@"/Users/user/Desktop/360zip.exe"];
[[NSFileManager defaultManager] moveItemAtURL:location toURL:savePath error:nil]; }]; [downTask resume];

3: 异步上传文件

 NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSData *data = ...; NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
// ...
}]; [uploadTask resume];

参考:http://objccn.io/issue-5-4/