Comment accepter un certificate SSL auto-signé à l'aide de NSURLSession d'iOS 7?

J'ai le code suivant (implémentation rapide):

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool { return protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust } func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if challenge.protectionSpace.host == "myDomain" { let credentials = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust) challenge.sender.useCredential(credentials, forAuthenticationChallenge: challenge) } } challenge.sender.continueWithoutCredentialForAuthenticationChallenge(challenge) } 

Il fonctionne parfaitement dans iOS 8.x, mais ne fonctionne pas iOS 7.x Dans iOS 7.x j'ai une erreur:

Echec du chargement HTTP NSURLConnection / CFURLConnection (kCFStreamErrorDomainSSL, -9813)

Une idée? Je vous remercie!!!

Les deux connection:canAuthenticateAgainstProtectionSpace: et connection:didReceiveAuthenticationChallenge: sont de toute façon obsolètes dans iOS 8, donc vous devriez utiliser d'autres methods.

Ce que j'utilise dans mes projets est une méthode déléguée de NSURLSessionDelegate. Adhérez à ce protocole puis ajoutez cette méthode:

 func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)) } 

Ensuite, lorsque vous utilisez initialiser NSURLSession avec délégué défini sur self. Par exemple:

 var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue()) 

Utilisez ensuite cette instance de session pour appeler la méthode dataTaskWithRequest sur:

 var task = session.dataTaskWithRequest(request){ (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in if error != nil { callback("", error.localizedDescription) } else { var result = NSSsortingng(data: data, encoding: NSASCIISsortingngEncoding)! } } task.resume() 

L'exemple de travail complet peut être trouvé ici .

Pour des raisons de security, si vous utilisez un certificate auto-signé, je recommand également d'implémenter l'épinglage de la key publique ( https://gist.github.com/edwardmp/df8517aa9f1752e73353 )

hérite de la class avec URLSessionDelegate

créer un object de session

 let config = URLSessionConfiguration.default let session = Foundation.URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main) let task = session.dataTask(with: httpRequest as URLRequest, completionHandler: {requestData, response, errorData -> Void in if errorData == nil { dataCallback(requestData! as NSData) } else { let error = NSError(domain: "Err-1001", code: 11, userInfo:nil) failureCallback(error) } }); task.resume() 

Ajouter un délégué

 func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { completionHandler( .useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!)) } 

ajoutez ceci dans votre file info.plist

 <key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>xyc.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true/> <key>NSExceptionRequiresForwardSecrecy</key> <true/> <key>NSExceptionMinimumTLSVersion</key> <ssortingng>TLSv1.2</ssortingng> <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key> <false/> <key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <true/> <key>NSThirdPartyExceptionMinimumTLSVersion</key> <ssortingng>TLSv1.2</ssortingng> <key>NSRequiresCertificateTransparency</key> <false/> </dict> </dict> </dict>