我正在尝试从UIWebView连接到使用Swift 3通过https使用自签名证书的服务器。我已经在我的iOS设备上安装了证书,我可以使用iOS上的Safari连接到服务器,所以问题位于应用程序内。
我在这里使用Objective C描述了我发现的最佳方法:
UIWebView to view self signed websites (No private api, not NSURLConnection) - is it possible?
我试图将其翻译成Swift 3,如下所示:
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
// other stuff
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print("HTTPSSETUP should start load with request: authenticated \(authenticated)")
if(!authenticated) {
print("HTTPSSETUP not yet authenticated - trying")
globalRequest = request
let conn: NSURLConnection = NSURLConnection(request: request, delegate: self)!
conn.start()
return false
}
// some other stuff
return true
}
func connection(_ connection: NSURLConnection, willSendRequestFor challenge: URLAuthenticationChallenge) {
print("HTTPSSETUP In willSendRequestForAuthenticationChallenge..");
challenge.sender!.use(URLCredential(trust: challenge.protectionSpace.serverTrust!),for: challenge)
challenge.sender!.continueWithoutCredential(for: challenge)
}
func connection(_ connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: URLProtectionSpace) -> Bool {
print("HTTPSSETUP can authenticate against protection space")
return true
}
func connection(_ connection: NSURLConnection, didReceive challenge: URLAuthenticationChallenge) {
print("HTTPSSETUP did receive authentication challenge")
if(challenge.previousFailureCount == 0) {
authenticated = true
let credential: URLCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
challenge.sender?.use(credential, for: challenge)
} else {
challenge.sender?.cancel(challenge)
}
}
func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
print("HTTPSSETUP did receive response")
authenticated = true
self.webView.loadRequest(globalRequest)
connection.cancel()
}
func connection(_ connection: NSURLConnection, didFailWithError error: Error) {
print("HTTPSSETUP did fail with error: " + error.localizedDescription)
}
这是控制台中的输出:
HTTPSSETUP should start load with request: authenticated false
HTTPSSETUP not yet authenticated - trying
2016-12-22 10:35:22.747238 AppName[916:341139] [] nw_coretls_read_one_record tls_handshake_process: [-9824]
2016-12-22 10:35:22.748404 AppName[916:341215] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824)
HTTPSSETUP did fail with error: An SSL error has occurred and a secure connection to the server cannot be made.
所以基本上 - 我看到的方式 - 主要问题如下:它从未收到URLAuthenticationChallenge(或发送请求) - 因此失败。我添加了两个方法“canAuthenticateAgainstProtectionSpace protectionSpace”以及“willSendRequestFor challenge:URLAuthenticationChallenge” - 我知道使用willSendRequestFor时不会调用canAuthenticateAgainstProtectionSpace。无论我删除哪个功能,它都不起作用。
有没有人知道如何使用Swift 3解决这个问题?任何帮助将不胜感激。