首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WKWebView授权

WKWebView授权
EN

Stack Overflow用户
提问于 2016-10-21 21:14:55
回答 1查看 1.8K关注 0票数 1

我想打开一个网站,使用WKWebView中的密码/用户名(基本)授权。

为此,我使用了didReceiveAuthenticationChallenge方法。

代码语言:javascript
复制
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

但由于某些原因,它不起作用。

添加代码行

代码语言:javascript
复制
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)。

希望你能帮助我。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2016-10-21 21:23:13

在您的代码中,您尚未将web视图的导航委托设置为您的控制器。

将控制器的定义更改为:

代码语言:javascript
复制
class ViewController: UIViewController, WKNavigationDelegate

在创建web视图之后,将导航代理设置为控制器:

代码语言:javascript
复制
webView.navigationDelegate = self

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40177660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档