Authentication with WKWebView in Swift

前端 未结 3 1989
长发绾君心
长发绾君心 2020-12-06 09:53

In my iOS app, I would like to use a WKWebView to wrap an external URL in the application. This URL requires basic authentication (it needs user and password credential, lik

3条回答
  •  清歌不尽
    2020-12-06 10:38

    In a simpler way:

    Though this answer looks redundant but posting as this may help other naive developers (like me).

       func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
            guard (webView.url?.host) != nil else {
                return
            }
            let authenticationMethod = challenge.protectionSpace.authenticationMethod
            if authenticationMethod == NSURLAuthenticationMethodDefault || authenticationMethod == NSURLAuthenticationMethodHTTPBasic || authenticationMethod == NSURLAuthenticationMethodHTTPDigest {
                let credential = URLCredential(user: userName, password: password, persistence: .none)
                completionHandler(.useCredential, credential)
            } else if authenticationMethod == NSURLAuthenticationMethodServerTrust {
                completionHandler(.performDefaultHandling, nil)
            } else {
                completionHandler(.cancelAuthenticationChallenge, nil)
            }
        }
    

提交回复
热议问题