NSURLSessionDownloadTask

NSURLSessionDownloadTask

我有NSURLSessionDownloadTask,正在加载大文件。尝试检查自服务器上的特定时间戳以来是否已对其进行修改。服务器(无法控制的服务器)似乎不支持If-Modified-Since标头。

我想获取“修改日期”标头,将其与我的值进行比较,如果它较旧,请不要下载。是否可以使用NSURLSessionDownloadTask来做到这一点,或者我必须改用NSURLSessionDateTask

最佳答案

您需要以下delegateNSURLSession方法

@protocol NSURLSessionDataDelegate <NSURLSessionTaskDelegate>
@optional
/* The task has received a response and no further messages will be
 * received until the completion block is called. The disposition
 * allows you to cancel a request or to turn a data task into a
 * download task. This delegate message is optional - if you do not
 * implement it, you can get the response as a property of the task.
 *
 * This method will not be called for background upload tasks (which cannot be converted to download tasks).
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
                                 didReceiveResponse:(NSURLResponse *)response
                                  completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler;


以及NSURLSessionDownloadTask的以下取消方法

@interface NSURLSessionDownloadTask : NSURLSessionTask

    /* Cancel the download (and calls the superclass -cancel).  If
     * conditions will allow for resuming the download in the future, the
     * callback will be called with an opaque data blob, which may be used
     * with -downloadTaskWithResumeData: to attempt to resume the download.
     * If resume data cannot be created, the completion handler will be
     * called with nil resumeData.
     */
    - (void)cancelByProducingResumeData:(void (^)(NSData * _Nullable resumeData))completionHandler;


收到完整的响应标头后,将立即调用上述委托方法,因此您可以验证相应的字段并做出继续还是取消的决定。

07-26 09:40