LoginSignup
43
43

More than 5 years have passed since last update.

WKWebView で Basic 認証がかかったページへアクセスする方法

Posted at

WKWebView では WKNavigationDelegate
webView:didReceiveAuthenticationChallenge:completionHandler:
を実装することになります。

認証が必要なサイトにアクセスした場合、ユーザー名、パスワードの入力を求めるアラートを表示するようにしてみました。

webkitdemo-authentication_required.png

    func webView(webView: WKWebView!, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
        let alertController = UIAlertController(title: "Authentication Required", message: webView.URL.host, preferredStyle: .Alert)
        weak var usernameTextField: UITextField!
        alertController.addTextFieldWithConfigurationHandler { textField in
            textField.placeholder = "Username"
            usernameTextField = textField
        }
        weak var passwordTextField: UITextField!
        alertController.addTextFieldWithConfigurationHandler { textField in
            textField.placeholder = "Password"
            textField.secureTextEntry = true
            passwordTextField = textField
        }
        alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
            completionHandler(.CancelAuthenticationChallenge, nil)
        }))
        alertController.addAction(UIAlertAction(title: "Log In", style: .Default, handler: { action in
            let credential = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.ForSession)
            completionHandler(.UseCredential, credential)
        }))
        self.presentViewController(alertController, animated: true, completion: nil)
    }

何か見覚えがあるメソッドですね。
NSURLSessionDelegateURLSession:didReceiveChallenge:completionHandler: とほとんど同じですね。
認証に必要な情報を NSURLCredential にセットして completionHandler を呼び出します。

注意点として、completionHandler は必ず呼び出す必要があります。
試しに Log In ボタン、あるいはキャンセルボタンがタップされたときの処理にある completionHandler の呼び出しをコメントアウトして実行してみると以下のエラーが発生しました。

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Completion handler passed to -[WebKitDemo.WebViewController webView:didReceiveAuthenticationChallenge:completionHandler:] was not called'

ソースコードは GitHub で WKWebView を使ったサンプルアプリとして公開しています。
https://github.com/qmihara/WebKitDemo

参考

43
43
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
43