在Swift中使用WKWebView进行身份validation

在我的iOS应用程序中,我想使用WKWebView在应用程序中封装外部URL。 这个URL需要基本的authentication(它需要用户和密码凭证,就像下面的截图一样)。

在这里输入图像说明

经过一番调查,我试图使用didReceiveAuthenticationChallenge方法,为了启用一个自动login,所以我不理解它是如何工作的。

这是我的代码。

 import UIKit import WebKit class WebViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView? private var request : NSURLRequest { let baseUrl = "https://unimol.esse3.cineca.it/auth/Logon.do" let URL = NSURL(string: baseUrl)! return NSURLRequest(URL: URL) } /* Start the network activity indicator when the web view is loading */ func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation){ UIApplication.sharedApplication().networkActivityIndicatorVisible = true } /* Stop the network activity indicator when the loading finishes */ func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation){ UIApplication.sharedApplication().networkActivityIndicatorVisible = false } func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: ((WKNavigationResponsePolicy) -> Void)){ decisionHandler(.Allow) } func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { if challenge.protectionSpace.host == "https://unimol.esse3.cineca.it/auth/Logon.do" { let user = "*******" let password = "******" let credential = NSURLCredential(user: user, password: password, persistence: NSURLCredentialPersistence.ForSession) challenge.sender?.useCredential(credential, forAuthenticationChallenge: challenge) } } override func viewDidLoad() { /* Create our preferences on how the web page should be loaded */ let preferences = WKPreferences() preferences.javaScriptEnabled = false /* Create a configuration for our preferences */ let configuration = WKWebViewConfiguration() configuration.preferences = preferences /* Now instantiate the web view */ webView = WKWebView(frame: view.bounds, configuration: configuration) if let theWebView = webView { /* Load a web page into our web view */ let urlRequest = self.request theWebView.loadRequest(urlRequest) theWebView.navigationDelegate = self view.addSubview(theWebView) } } } 

我面临着这个例外:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Completion handler passed to -[MyUnimol.WebViewController webView:didReceiveAuthenticationChallenge:completionHandler:] was not called'

如果我删除了didReceiveAuthenticationChallenge方法,我可以到达URL,但却给我留下了错误的凭据。

任何人都可以解释我做错了吗?

添加以下行:

 completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential) 

didReceiveAuthenticationChallenge结束时解决了这个问题。