1. 程式人生 > >NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, 9813)

NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, 9813)

遇到Obj-C 存取 self sign ssl 時會顯示 error:

NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)

解法:

For me your first example is working fine. I have tested with the following code without problems (it is of course very insecure since it allows any server certificate).

@implementation
SessionTest - (void) startSession { NSURL *url = [NSURL URLWithString:@"https://self-signed.server.url"]; NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration
: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]]; NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if
(error == nil) { NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog(@"Data: %@",text); } else { NSLog(@"Error: %@", error); } }]; [dataTask resume]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]); } @end

Update: This is the class interface, the SessionTest class is the NSURLSessionDataDelegate, to start the data download you create a SessionTest object and call the startSession method.

@interface SessionTest : NSObject <NSURLSessionDelegate>

- (void) startSession;

@end

或這個範例:

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:Nil];
...
...
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
  if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
    if([challenge.protectionSpace.host isEqualToString:@"mydomain.com"]){
      NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
      completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
    }
  }
}