Swift: WKWebView 需要认证。
Swift: WKWebView needs authentication.
我正在尝试将 WKWebView 添加到我的应用程序。根据文档,我实现了这个:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string: "www.myurl.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
}
现在我的问题是:我尝试访问的网站需要身份验证。在野生动物园中,我被要求。但我的应用程序只显示错误“404 - 此网站不存在”。经过搜索,我得到的信息是接收 URLAuthenticationChallenge 可以解决问题。借助网上的文档和资料,我添加了以下代码:
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("test if pass")
let user = "*****"
let password = "*****"
let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
challenge.sender?.use(credential, for: challenge)
}
我添加了 print 语句以查看是否进入我的代码。但是在启动我的应用程序后仍然出现 404 错误并且没有任何内容打印到我的控制台。
有人可以帮助我如何添加身份验证吗?谢谢:)
更新你的线路,
let myURL = URL(string: "www.myurl.com")
和
let myURL = URL(string: "http://username:password@myURL.com/)
这可以帮助我解决与您相同的问题。希望这对你也有帮助。
我正在尝试将 WKWebView 添加到我的应用程序。根据文档,我实现了这个:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string: "www.myurl.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
}
现在我的问题是:我尝试访问的网站需要身份验证。在野生动物园中,我被要求。但我的应用程序只显示错误“404 - 此网站不存在”。经过搜索,我得到的信息是接收 URLAuthenticationChallenge 可以解决问题。借助网上的文档和资料,我添加了以下代码:
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("test if pass")
let user = "*****"
let password = "*****"
let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
challenge.sender?.use(credential, for: challenge)
}
我添加了 print 语句以查看是否进入我的代码。但是在启动我的应用程序后仍然出现 404 错误并且没有任何内容打印到我的控制台。
有人可以帮助我如何添加身份验证吗?谢谢:)
更新你的线路,
let myURL = URL(string: "www.myurl.com")
和
let myURL = URL(string: "http://username:password@myURL.com/)
这可以帮助我解决与您相同的问题。希望这对你也有帮助。