NSURLSession和NSURLConnection

来源:互联网 发布:商务双肩包 知乎 编辑:程序博客网 时间:2024/06/06 13:23

网络请求核心库从iOS7之后已经从NSURLConnection换成了NSURLSession了。那么问题就来了,为什么要换,优点缺点是什么?带着疑问开始追寻。
先一张图NSURLSession的框架。
NSURLSession的核心类框架图
现在AFNetWorking的核心网络请求逻辑就是使用这三个类。

  1. NSURLConnection的缺点

    • 缺点1

直接先来一个苹果文档的解释。

@discussion        The interface for NSURLConnection is very sparse, providing        "only****" the controls to start and cancel asynchronous loads of a        URL request.

苹果在文档中着重强调only,不知道没有出NSURLSession的时候有没有,我估计没有(意淫)之前没有主意解释。因为只有start和cancel,那么cancel之后重新开始呢,你想对了只能重新开始。那问题来了,NSURLSession有什么牛逼之处呢?
下边是NSURLSessionTask文档代码:

/* -cancel returns immediately, but marks a task as being canceled. * The task will signal -URLSession:task:didCompleteWithError: with an * error value of { NSURLErrorDomain, NSURLErrorCancelled }.  In some  * cases, the task may signal other work before it acknowledges the  * cancelation.  -cancel may be sent to a task that has been suspended. */- (void)cancel;/* * Suspending a task will prevent the NSURLSession from continuing to * load data.  There may still be delegate calls made on behalf of * this task (for instance, to report data received while suspending) * but no further transmissions will be made on behalf of the task * until -resume is sent.  The timeout timer associated with the task * will be disabled while a task is suspended. -suspend and -resume are * nestable.  */- (void)suspend;- (void)resume;来自:NSURLSession.h 

变为3个方法:cancel,suspend,resume。意味着暂停之后还能继续请求。是不是灵活很多。

  • 缺点2

    An NSURLConnection may be used for loading of resource data
    directly to memory, in which case an
    NSURLConnectionDataDelegate should be supplied, or for
    downloading of resource data directly to a file, in which case
    an NSURLConnectionDownloadDelegate is used. The delegate is
    retained by the NSURLConnection until a terminal condition is
    encountered. These two delegates are logically subclasses of
    the base protocol, NSURLConnectionDelegate.<p>

NSURLSession

 An NSURLSessionDownloadTask will directly write the response data to a temporary file.  When completed, the delegate is sent URLSession:downloadTask:didFinishDownloadingToURL: and given an opportunity  to move this file to a permanent location in its sandboxed container, or to otherwise read the file. If canceled, an NSURLSessionDownloadTask can produce a data blob that can be used to resume a download at a later time.

一个在内存一个在沙盒,显然前者更耗内存。

  • 缺点3

    断点续传
    NSURLConnection进行断点下载,通过设置访问请求的HTTPHeaderField的Range属性,开启运行循环,NSURLConnection的代理方法作为运行循环的事件源,接收到下载数据时代理方法就会持续调用,并使用NSOutputStream管道流进行数据保存。
    NSURLSession进行断点下载,当暂停下载任务后,如果 downloadTask (下载任务)为非空,调用 cancelByProducingResumeData:(void (^)(NSData *resumeData))completionHandler 这个方法,这个方法接收一个参数,完成处理代码块,这个代码块有一个 NSData 参数 resumeData,如果 resumeData 非空,我们就保存这个对象到视图控制器的 resumeData 属性中。在点击再次下载时,通过调用 [ [self.session downloadTaskWithResumeData:self.resumeData]resume]方法进行继续下载操作。
    经过以上比较可以发现,使用NSURLSession进行断点下载更加便捷。

- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandlerDescription Creates a download task to resume a previously canceled or failed download and calls a handler upon completion. The task bypasses calls to delegate methods for response and data delivery, and instead provides any resulting NSURL, NSURLResponse, and NSError objects inside the completion handler. Delegate methods for handling authentication challenges, however, are still called.The new session download task.Parameters  resumeData  A data object that provides the data necessary to resume the download.completionHandler   The completion handler to call when the load request is complete. This handler is executed on the delegate queue.If you pass nil, only the session delegate methods are called when the task completes, making this method equivalent to the downloadTaskWithResumeData: method.locationThe location of a temporary file where the server’s response is stored. You must move this file or open it for reading before your completion handler returns. Otherwise, the file is deleted, and the data is lost.responseAn object that provides response metadata, such as HTTP headers and status code. If you are making an HTTP or HTTPS request, the returned object is actually an NSHTTPURLResponse object.errorAn error object that indicates why the request failed, or nil if the request was successful.

以后有新的研究继续更新。有问题大家随时评论,共同学习
参考思路:http://www.cnblogs.com/kakaluote123/articles/5426923.html

0 0
原创粉丝点击