Swift 2 - Xcode 7.0 Cannot Access HTTPS site with unstrusted SSL Certificate

前端 未结 5 861
死守一世寂寞
死守一世寂寞 2021-02-06 01:00

Experts, I\'m a Beginner in IOS 9 / XCODE 7 / Swift 2 Development Kit

I\'m trying to create an ios app that simply route to Web Application in HTTPS protocol. Below is

5条回答
  •  梦如初夏
    2021-02-06 01:08

    In Swift 3.

    Step 1. Add NSURLConnectionDelegate to your viewcontroller, to overwrite methods.

    class ViewController: UIViewController, NSURLConnectionDelegate {
    

    Step 2. Override viewDidLoad

    override func viewDidLoad() {
            super.viewDidLoad()
    
            let siteAddress = "https://mysiteaddress"
            let url = URL(string: siteAddress)
            let urlRequest = URLRequest(url: url!)
            let urlConnection:NSURLConnection = NSURLConnection(request: urlRequest, delegate: self)!
            webView.loadRequest(urlRequest)
        }
    

    Step 3 Overwrite canAuthenticateAgainstProtectionSpace and didReceive challenge

    func connection(_ connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: URLProtectionSpace) -> Bool {
        print("\ncanAuthenticateAgainstProtectionSpace method Returning True\n")
        return true
    }
    
    func connection(_ connection: NSURLConnection, didReceive challenge: URLAuthenticationChallenge) {
        print("did autherntcationchallenge = \(challenge.protectionSpace.authenticationMethod)")
    
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust  {
            print("\nsend credential Server Trust\n")
            let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
            challenge.sender!.use(credential, for: challenge)
    
        }else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic{
            print("send credential HTTP Basic")
            let defaultCredentials: URLCredential = URLCredential(user: "user", password: "password", persistence:URLCredential.Persistence.forSession)
            challenge.sender!.use(defaultCredentials, for: challenge)
    
        }else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM{
            print("\nsend credential NTLM\n")
    
        } else{
            challenge.sender!.performDefaultHandling!(for: challenge)
        }
    
    }
    

    Thanks Navas Basheer for the original solution! Saved me a ton of time

提交回复
热议问题