How do I accept a self-signed SSL certificate using iOS 7's NSURLSession

前端 未结 3 1573
星月不相逢
星月不相逢 2020-12-29 08:16

I have the following code (swift implementation):

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLPr         


        
3条回答
  •  自闭症患者
    2020-12-29 09:17

    Both connection:canAuthenticateAgainstProtectionSpace: and connection:didReceiveAuthenticationChallenge: are deprecated in iOS 8 anyway so you should use other methods.

    What I am using in my projects is a delegate method of NSURLSessionDelegate. Adhere to that protocol then add this method:

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

    Then, when you use initialize NSURLSession with delegate set to self. For example:

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

    Then use that session instance to call dataTaskWithRequest method on:

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

    Complete working example can be found here.

    For security reasons, if you use a self-signed certificate I recommend also implementing public key pinning (https://gist.github.com/edwardmp/df8517aa9f1752e73353)

提交回复
热议问题