Ios – How to accept a self-signed SSL certificate using iOS 7’s NSURLSession and its family of delegate methods for development purposes

iosios7iphoneobjective cssl

I am developing an iPhone app. During development, I need to connect to a server that's using a self-signed SSL certificate. I'm pretty certain - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler is my opportunity to write some exception code to allow this. However, I can't find any resources that tell me how to do this. I can see the following error in the log:

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

In addition to this, when I NSLog(@"error = %@", error); from within the above delegate method I get:

Error Domain=NSURLErrorDomain Code=-1202 "The certificate for
this server is invalid. You might be connecting to a server that is
pretending to be “api.mydevelopmenturl.com” which could put your
confidential information at risk." UserInfo=0x10cbdbcf0
{NSUnderlyingError=0x112ec9730 "The certificate for this server is
invalid. You might be connecting to a server that is pretending to be
“api.mydevelopmenturl.com” which could put your confidential information
at risk.", NSErrorFailingURLStringKey=https://api.mydevelopmenturl.com/posts,
NSErrorFailingURLKey=https://api.mydevelopmenturl.com/posts,
NSLocalizedRecoverySuggestion=Would you like to connect to the
server anyway?, NSURLErrorFailingURLPeerTrustErrorKey=,
NSLocalizedDescription=The certificate for this server is invalid.
You might be connecting to a server that is pretending to be
“api.mydevelopmenturl.com” which could put your confidential
information at risk.}

Any ideas on how to resolve this issue? Please post code as I've read the conceptual docs and I don't understand them. Here's an example of one that's beyond me: https://developer.apple.com/library/content/technotes/tn2232/_index.html

Best Answer

This works for me:

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);
    }
  }
}
Related Topic