如何从NSURLSessionDownloadTask downloadTaskWithRequest获得响应

时间:2015-09-11 18:48:34

标签: ios objective-c amazon-web-services nsurlsession nsurlsessiondownloadtask

首先是背景: 应用程序应该从AWS S3服务器获取文件。为了做到这一点,该过程的第一步是转到本地服务器并从中获取文件的名称和一些其他信息。在该步骤之后,我们有一个完整的 URLMutableRequest

注意:我将NSURLSession设置为后台会话:

select program_name, provider_name, patient_name, service_date
from tablename
group by program_name, provider_name, patient_name, service_date
having count(*) > 1

这是从AWS S3服务器下载文件的任务:

执行此任务我想使用委托在后台模式下运行。

- (NSURLSession *)backgroundSession
{
    static NSURLSession *session = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"identifier"];
        session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    });
    return session;
}

如何从此请求获得响应?

Apple文档说,在使用@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask; @property (nonatomic, strong) NSURLSession *defaultSession; self.defaultSession = [self backgroundSession]; self.downloadTask = [self.defaultSession downloadTaskWithRequest:request]; [self.downloadTask resume]; 时,您不能将块作为completionHandler。

3 个答案:

答案 0 :(得分:5)

如果有人想知道如何在下载完成之前获得下载响应,请尝试以下操作:取消dataTask,获取响应,然后根据需要将dataTask转换为下载。

NSURLSessionTask *task = [session dataTaskWithRequest:request];
[task resume];

NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    // use response, convert data task to download task
    completionHandler(NSURLSessionResponseBecomeDownload);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask {
    // downloadTask converted from dataTask
}

NSURLSessionDownloadDelegate

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    // update progress
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    // copy downloaded file from location
}

答案 1 :(得分:1)

NSURLSessionDownloadTask具有response属性(其基类的一部分,NSURLSessionTask),应设置为响应。请参阅here

答案 2 :(得分:0)

您需要在班级中实施NSURLSessionDownloadDelegate协议(因为您已将会话委托指定为self)。

您应该查看可用方法的文档,但您至少要实现以下内容:

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data