ios - WKWebView授权

标签 ios swift wkwebview

我想在 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)。

希望你能帮助我。 谢谢!

最佳答案

在您的代码中,您没有将 WebView 的导航委托(delegate)设置为您的 Controller 。

将 Controller 的定义更改为:

class ViewController: UIViewController, WKNavigationDelegate

在创建您的 WebView 后,将导航委托(delegate)设置为您的 Controller :

webView.navigationDelegate = self

根据您是否使用 Swift 3,您可能需要将方法的签名更改为 webView(_:didReceive:completionHandler:) .

关于ios - WKWebView授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40177660/

相关文章:

ios - Angular 2 应用程序 : route content is blank on iOS

ios - 清理后,managedObjectContext 为 nil 并导致 fatal error : unexpectedly found nil while unwrapping an optional value

ios - React native, View 中的 RCT_EXPORT_METHOD

ios - 从 Swift 中的另一个 View Controller 访问 TableView 单元格信息

ios - SwiftUI:如何使 TextField 适合多行内容?

ios - UIWebview中的嵌套stringByEvaluatingJavaScript迁移到WKWebview

ios - 在哪里/如何手动处理 WKWebView estimatedProgress 的观察者

javascript - WkWebView Evaluatejavascript 返回不支持的类型错误

ios - 登录 swift ios 应用程序后在哪里存储用户信息

iOS 14 : Allow Location Access | Always menu not found