K.Krueger
K.Krueger

Reputation: 11

WKWebView Authorization

I am would like open a website, using a password/username (basic)Authorization in a WKWebView.
To do that I use the method 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

But for some reason, it does not work.
Adding the code line

completionHandler(URLSession.AuthChallengeDisposition.UseCredential, credential)

like in the description here: Authentication with WKWebView in Swift produced an error.
I have also tried to change the challenge.protectionSpace.host into vplan.bielefeld-marienschule.logoip.de:443 which is shown as the login adress in the Safari pop-up and into the IP-Adress of the server (93.206.31.253).

Hope you can help me. Thank You!

Upvotes: 1

Views: 2420

Answers (1)

Léo Natan
Léo Natan

Reputation: 57060

In your code, you have not set the navigation delegate of the web view to your controller.

Change the definition of your controller to:

class ViewController: UIViewController, WKNavigationDelegate

And after creating your web view, set the navigation delegate to your controller:

webView.navigationDelegate = self

Depending on if you are using Swift 3, you may need to change the signature of the method to webView(_:didReceive:completionHandler:).

Upvotes: 2

Related Questions