NSURLSession身份验证和后台下载文件

时间:2014-02-04 06:37:40

标签: ios nsurlsession

在iPad应用中,我需要连接到服务器并在后台模式下使用带有NSURLSession对象的自签名SSL证书下载文件:

static NSString *const URL = @"https://...";

- (void)testBackgroundDownloadTask {
    if (self.downloadTask) {
        return self;
    }
    self.session = [self backgroundSession];
    NSURL *downloadURL = [NSURL URLWithString:URL];
    NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
    self.downloadTask = [self.session downloadTaskWithRequest:request];
    [self.downloadTask resume];
}

- (NSURLSession *)backgroundSession{
    static NSURLSession *sess = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:URL];
        // Default configuration: working perfectly
        //NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.sessionSendsLaunchEvents = YES;
    //configuration.TLSMinimumSupportedProtocol = kSSLProtocolAll;
    configuration.networkServiceType = NSURLNetworkServiceTypeBackground;
        sess = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    });
    return sess;
}

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
    NSURLProtectionSpace *protectionSpace = challenge.protectionSpace;
    NSString *authMethod = protectionSpace.authenticationMethod;

    if ([authMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
        // obtain challenge, it working with NSURLSession in default session config 
        [self.challengeHandler handleChallenge:challenge onCompletion:^(id obj) {
            NSURLCredential *c = (NSURLCredential *)obj;
            if (c) {
                [challenge.sender useCredential:c forAuthenticationChallenge:challenge];
                completionHandler(NSURLSessionAuthChallengeUseCredential, c);
            }
            else {
                [challenge.sender cancelAuthenticationChallenge:challenge];
            }
        }];
    }
    else if ([authMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
    }
}

如果我使用defaultSessionConfiguration,我的应用后调用didReceiveChallenge方法会成功下载文件(调用NSURLSesionDownloadDelegate方法

– URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes: 
– URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite: 
– URLSession:downloadTask:didFinishDownloadingToURL: 

但我使用backgroundSessionConfiguration,在调用didReceiveChallenge之后没有调用其他委托的方法(文件未下载而didCompleteWithError未调用) 关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:0)

  1. 您是在后台测试吗?

  2. NSURLSessionDownloadDelegate上,您应该会看到实施时获得的内容

    - (void)URLSession:(NSURLSession *)session 
        task:(NSURLSessionTask *)task 
        didCompleteWithError:(NSError *)error
    {
        NSLog(@"%s %@ %@", __PRETTY_FUNCTION__, task.response, error);
    }    
    
  3. 如果–URLSession:didReceiveChallenge:completionHandler:中的任何内容都是异步的,那么您需要使用UIApplication / UIBackgroundTaskIdentifier {begin,{{1} }} end,或iOS会在堆栈弹出时终止你的后台进程。