如何获取 KVO #keyPath(WKWebView.url) 的 URL 值?



我发布了一个更深入的问题,试图深入了解问题的根源,但简要介绍一下:

我正在尝试通过WKWebView展示基于PHP/JS的Web应用程序(Laravel(。但是,由于脚本重定向属性的性质,我得到的唯一实际检测 URL 更改的代码是#keyPath(WKWebView.url)

override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
webView.uiDelegate = self    
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.url), options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(WKWebView.url) {
print("URL Change:", self.webView.url?.absoluteString ?? "# No value provided")
}
}

但是,控制台的输出始终相同:

URL Change: # No value provided

所以我知道WKWebView.url的KVO能够在WebView中基于脚本的重定向时触发。事实上,如果你看看我的另一个问题,它是唯一可以检测到这种重定向的代码——这很奇怪,因为当在 Safari(iOS 和 macOS(中启动时,URL 栏能够反映那些重定向的更改URL的值。但是,在 WKWebView 中,没有任何 WKNavigationDelegate 函数能够检测到对 URL 的此类更改。

有没有办法在触发时直接从 WKWebView.url 的 keyPath 值获取 URL?是否有任何替代方法,在我之前提到的问题中没有描述,可以获得 URL?

尝试从webView.url获取 URL 值似乎总是返回 nil。

编辑:我能够使用观察者值函数代码获取确切的 URL 值:

if let key = change?[NSKeyValueChangeKey.newKey] {
print("URL: (key)") // url value
}

但是,我无法将其转换为字符串或将其传递给另一个函数。有没有办法将此键设置为变量,如果它 .contains("https://"(?

我能够将 KVOWKWebView.url分配给字符串变量。从那里,我能够将 String 值传递给一个函数,然后该函数处理我正在寻找的每个输出:

var cURL = ""
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let key = change?[NSKeyValueChangeKey.newKey] {
cURL = "(key)"         // Assign key-value to String
print("cURL:", cURL)    // Print key-value
cURLChange(url: cURL)   // Pass key-value to function
}
}
func cURLChange(url: String) {
if cURL.contains("/projects/new") {
print("User launched new project view")
// Do something
} else {
// Do something else
}
}

这里提供了类似的解决方案,使用更现代的方法(麻烦更少(。

var cURL = ""
var webView: WKWebView!
var webViewURLObserver: NSKeyValueObservation?
override func viewDidLoad() {
super.viewDidLoad()
// 1. Assign changed value to variable
webViewURLObserver = webView.observe(.url, options: .new) { webView, change in
self.cURL = "(String(describing: change.newValue))" }
// 2. Print value of WKWebView URL
webViewURLObserver = webView.observe(.url, options: .new) { webView, change in
print("URL: (String(describing: change.newValue))"
)}

通过使用对象的 NSKeyValueObservation,您无需通过 keyPath 删除观察器或检查观察器值。您可以简单地将其设置为观察对象(即。WKWebView(,并在观察到更改时运行代码。

最新更新