我想在WKWebView中使用密码/用户名(基本)授权打开一个网站
为此,我使用方法didReceiveAuthenticationChallenge
。
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet weak var container: UIView!
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView = WKWebView()
container.addSubview(webView)
let urlStr = "https://vplan.bielefeld-marienschule.logoip.de/subst_002.htm"
let url = NSURL(string: urlStr)!
let request = NSURLRequest(url: url as URL)
webView.load(request as URLRequest)
}
func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void){
if challenge.protectionSpace.host == "https://vplan.bielefeld-marienschule.logoip.de/subst_002.htm" {
let userStr = "********"
let passwordStr = "********"
let credential = URLCredential(user: userStr, password: passwordStr, persistence: URLCredential.Persistence.forSession)
challenge.sender?.use(credential, for: challenge)
completionHandler(.useCredential, credential)
}
}
override func viewDidAppear(_ animated: Bool) {
let frame = CGRect(x: 0, y: 0, width: container.bounds.width, height: container.bounds.height)
webView.frame = frame
但由于某种原因,它不起作用 添加代码行
completionHandler(URLSession.AuthChallengeDisposition.UseCredential, credential)
就像在此处的说明中一样:Authentication with WKWebView in Swift产生了错误
我还尝试将challenge.protectionSpace.host
更改为vplan.bielefeld-marienschule.logoip.de:443
,在Safari pop-up中显示为登录地址,并进入服务器的IP地址(93.206.31.253)。
答案 0 :(得分:2)
在您的代码中,您尚未将Web视图的导航委托设置为控制器。
将控制器的定义更改为:
class ViewController: UIViewController, WKNavigationDelegate
创建Web视图后,将导航委托设置为控制器:
webView.navigationDelegate = self
根据您使用的是Swift 3,您可能需要将方法的签名更改为webView(_:didReceive:completionHandler:)
。