iOS_NSURLSession

  • 说明:

    • 本文将介绍NSURLSession, 使用NSURLSession实现下载数据. 博文底部会对文中所使用的方法有详细的介绍, 如果感兴趣可以仔细阅读.

    • NSURLSession有三种 session类型(由NSURLSessionConfiguration定义), 本文介绍第一种类型:default session.

    • NSURLSession 有三种任务(task), 分别对应三个类:(NSURLSessionDataTask, NSURLSessionUploadTask, NSURLSessionDownloadTask)

    • NSURLSession 使用步骤: 指定session类型->创建session对象-> 向session中添加任务(task). 可根据实际情况, 灵活使用下载任务类型和下载方法.

    • 代码中所使用到的接口(例: http://c.3g.163.com/photo/api/list/0096/4GJ60096.json) 都具有时效性, 建议测试时使用一个可以提供数据的新接口.

  • 文章中尽量不使用或少使用封装, 目的是让大家清楚为了实现功能所需要的官方核心API是哪些(如果使用封装, 会在封装外面加以注释)

  • 此文章由 @春雨 编写. 经 @Scott,@黑子 审核. 若转载此文章,请注明出处和作者

iOS中NSURLSession类

核心API

Class ::

  • NSURLSession,

  • NSURLSessionConfiguration,

  • NSURLSessionTask

    • NSURLSessionDataTask
    • NSURLSessionDownloadTask

Delegate : 无.

涉及的API :(API的官方详细注释详见本章结尾)


/** 使用类方法, 创建NSURLSessionConfiguration的对象.*/
+ (NSURLSessionConfiguration *)defaultSessionConfiguration

/** 使用类方法, 创建NSURLSession的对象. */
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration

/** 创建NSURLSessionDataTask类型的任务*/
- (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


/** 创建NSURLSessionDownloadTask类型的任务*/
- (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

/** 需要注意的是:
可以从官方API中看出, 上述四种方法中的completionHandler参数, 在没有签订代理人, 执行代理方法的情况下, 是不能为nil的. */



/** 调用此方法, 让任务开始. */
- (void)resume

功能实现

思路:
  1. 先创建一个NSURLSession的对象, 相当于在客户端和服务器之间建立一个会话.
  2. 在这个会话中可以创建一个或多个任务.(也可以是多种类型的任务).
Code:
I. 创建NSURLSession对象
    /** 1. 创建NSURLSessionConfiguration类的对象, 这个对象被用于创建NSURLSession类的对象. */

    NSURLSessionConfiguration *configur = [NSURLSessionConfiguration defaultSessionConfiguration];


    /**
     * 2. 创建NSURLSession的对象. 
     *
     * 参数一: NSURLSessionConfiguration类的对象.(第1步创建的对象.)
     *
     * 注: 此时我们所创建的NSURLSession类的对象mySession的行为和NSURLConnection类似.
     *
     * 官方API原文: default sessions that behave much like NSURLConnection.
     */

    NSURLSession *mySession = [NSURLSession sessionWithConfiguration:configur]; 
II . 在mySession会话中创建任务
创建一个NSURLSessionDataTask类型的任务
```oc
/** 3. 创建URL. */
NSURL *url = [NSURL URLWithString:@"http://c.3g.163.com/photo/api/list/0096/4GJ60096.json"];

/** 4. 创建request. */
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

request.HTTPMethod = @"GET"; /**-> 设置url的请求方式, 默认是GET. */



/**
 * 5. 利用mySession的方法创建一个NSURLSessionDataTask类型的任务.
 * 参数一: 一个NSURLRequest对象.
 * 参数二: 加载完成后所执行的block块.
 */
NSURLSessionDataTask *dataTask = [mySession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    /**
     * Block参数说明
     * 1. data 返回的数据
     * 2. response 返回的响应
     * 3. error 链接错误
     */

    /** 打印输出三个参数. */
    NSLog(@"data: %@", data);
    NSLog(@"respone: %@", response);

    /**
     * 在NSURLResponse类中有MIMEType属性, 它代表返回数据的类型, 例如: json, xml, jpg等等. 当你不知道返回的数据类型时, 可以用它来判断.
         */
    NSLog(@"MIMEType: %@", response.MIMEType);

    NSLog(@"error: %@", error);

    /** 处理获取到的数据. */
    NSError *er = nil;
    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&er];

    NSLog(@"result: %@", result);
}];

/**
 * 6. 根据官方API的描述: 
 * After you create the task, you must start it by calling its resume method.
 * 对于这个方法, 在看过很多官方API后, 我个人认为相当于开始任务的操作.
 */
[dataTask resume];

```
在mySession会话中再创建一个NSURLSessionDownloadTask类型的任务
    /** 重复上述 3, 4, 5, 6步骤(3, 4步骤可以合在一起). */

    NSMutableURLRequest *downloadRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://magicapi.vmovier.com/magicapi/find"]];

    downloadRequest.HTTPMethod = @"POST";

    /** 如果请求方式是POST, 还需要设置HTTPBody属性. */
    NSString *strBody = @"=1&p=1";

    NSData *bodyData = [strBody dataUsingEncoding:NSUTF8StringEncoding];
    downloadRequest.HTTPBody = bodyData;

    /**
     * 利用mySession的方法创建一个NSURLSessionDownloadTask类型的任务.
     * 参数一: 一个NSURLRequest对象.
     * 参数二: 加载完成后所执行的block块.
     */
    NSURLSessionDownloadTask *downloadTask = [mySession downloadTaskWithRequest:downloadRequest completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

        /**
         * Block参数说明
         * 1. location 根据返回的数据所存储的本地文件路径得到的URL.
         * 2. response 返回的响应
         * 3. error 链接错误
         */

        /** 打印输出三个参数. */
        NSLog(@"location: %@", location);
        NSLog(@"respone: %@", response);
        NSLog(@"MIMEType: %@", response.MIMEType);
        NSLog(@"error: %@", error);

        /** 根据location获取到下载的数据. */
        NSError *er = nil;
        NSData *data = [NSData dataWithContentsOfURL:location];
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&er];
        NSLog(@"download Data: %@", data);
        NSLog(@"download result: %@", result);

    }];

    [downloadTask resume];

注:

  • 当一个session中有多个或多种任务时, 可以使用NSURLSessionTask中的属性 taskIdentifier – 任务的唯一标示符(只在同一个session中是唯一的, 如果多个session, 标示符可能会相同.) 来区分.
  • NSURLSession中的 getTasksWithCompletionHandler: 方法可以获取同一个session中的所用任务.


API 官方注释

NSURLSessionConfiguration

/**
 * @brief   Returns a newly created default session configuration object.
 *
 * @return   A new configuration object for managing upload and download tasks using the default options.
 */

+ (NSURLSessionConfiguration *)defaultSessionConfiguration

NSURLSession

/**
 * @brief   Creates a session with the specified session configuration.
 *
 * @param   <configuration>     A configuration object that specifies certain behaviors, such as caching policies, timeouts, proxies, pipelining, TLS versions to support, cookie policies, credential storage, and so on. For more information, see NSURLSessionConfiguration Class Reference.
 */

+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration
/**
 * @brief   Creates an HTTP request for the specified URL request object, and calls a handler upon completion.
 *
 * @param   <request>       An NSURLRequest object that provides the URL, cache policy, request type, body data or body stream, and so on.information.
 * 
 * @param   <completionHandler>  The completion handler to call when the load request is complete. This handler is executed on the delegate queue.

Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.
 *
 * @return  The new session data task.
 */

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler
/**
 * @brief   Creates a download task for the specified URL request, saves the results to a file, and calls a handler upon completion.
 *
 * @param   <request>       An NSURLRequest object that provides the URL, cache policy, request type, body data or body stream, and so on.
 * 
 * @param   <completionHandler>     The completion handler to call when the load request is complete. This handler is executed on the delegate queue.

Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.
 *
 * @return  The new session download task.
 */

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler

NSURLSessionTask

/**
 * @brief   Resumes the task, if it is suspended.
 */

- (void)resume

解释说明 :

NSURLSession中还有两种创建任务的方法:

  • 创建Data Task:
    从brief中可以看出此方法只适用于GET请求方式, 这是需要注意的一点.

/**
  * @brief   Creates an HTTP GET request for the specified URL, then calls a handler upon completion.
  *
  * @param   <url>  The http or https URL to be retrieved.
  *
  * @param  <completionHandler>  The completion handler to call when the load request is complete. If sent to a session created by calling sessionWithConfiguration:delegate:delegateQueue: with a non-nil value for the delegateQueue parameter, this handler is executed on that delegate queue.

                        Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.
  * 
  * @return  The new session data task.
  */

- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler
  • 创建Download Task
虽然这个方法中没有明确的说明是GET请求方式, 但是提供的参数是NSURL类型, 
POST请求无法直接使用NSURL进行请求, 所以我个人认为这个方法也只适用于GET请求.
/**
  * @brief   Creates a download task for the specified URL, saves the results to a file, and calls a handler upon completion.
  *
  * @param   <url>  An NSURL object that provides the URL to download.
  *
  * @param  <completionHandler>  The completion handler to call when the load request is complete. This handler is executed on the delegate queue.

Unless you have provided a custom delegate, this parameter must not be nil, because there is no other way to retrieve the response data.
  * 
  * @return  The new session download task.
  */


- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值