Mat*_*ift 2 macos xcode ios swift wkwebview
我有一个呈现Laravel Web 应用程序的WKWebView。我目前有我的 ViewController 设置来捕获 URL 更改 - 它可以捕获大部分更改。但是,WKWebView 似乎忽略了通过 JavaScript 事件进行的少量 URL 更改。
我已经尝试了以下所有解决方案并在下面的代码中实现了它们:
在我展示代码之前有一个有趣的说明:它能够检测简单的 #hash 更改,但无法检测从第 1 页加载到第 2 页的 JavaScript 事件操作(这是我试图捕获的 URL 更改):
https://myweb.com/dashboard ? https://myweb.com/dashboard/projects/new
视图控制器.swift
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
@IBOutlet var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
webView.uiDelegate = self
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.url), options: .new, context: nil)
webView.load(URLRequest(url: URL(string: "https://myweb.com/")!))
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if object as AnyObject? === webView && keyPath == "URL" {
print("URL Change 1:", webView.url?.absoluteString ?? "No value provided")
}
if keyPath == #keyPath(WKWebView.url) {
print("URL Change 2:", self.webView.url?.absoluteString ?? "# No value provided")
}
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let webURL = webView.url?.absoluteString
let reqURL = navigationAction.request.url?.absoluteString
print("webURL:", webURL)
print("reqURL:", reqURL)
decisionHandler(.allow)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
let webURL = webView.url?.absoluteString
print("webURL:", webURL)
}
}
Run Code Online (Sandbox Code Playgroud)
有一段代码似乎在 JavaScript 事件操作上触发,那就是keyPath == #keyPath(WKWebView.url).
然而,它似乎只是触发了它,以及它的结果打印到控制台:(URL Change 2: # No value provided作为 nil 合并运算符的结果:self.webView.url?.absoluteString ?? "# No value provided".
意思是,这 2 行观察者代码是唯一可以捕获此更改的内容,但不返回该更改的值:
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.url), options: .new, context: nil)
if keyPath == #keyPath(WKWebView.url) {
print("URL Change 2:", self.webView.url?.absoluteString ?? "# No value provided")
}
Run Code Online (Sandbox Code Playgroud)
任何其他尝试检索此更改的值或强制解包它,都会在didStartProvisionalNavigation调用后立即导致启动时崩溃:
Xcode 错误
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Xcode 控制台日志
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/me/Apps/MyWeb/iOS/MyWeb/ViewController.swift, line 125
2020-02-11 12:47:55.169765-0500 MyWeb[3066:124221] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/me/Apps/MyWeb/iOS/MyWeb/ViewController.swift, line 125
(lldb)
Run Code Online (Sandbox Code Playgroud)
我如何能够输出该 URL 更改的值?同样,当我单击 JS 按钮加载页面时,它似乎是唯一触发的代码(或者至少,控制台是这么说的)。在 Safari 中,对于 iOS 和 MacOS,URL 更改似乎确实反映在 URL 搜索栏中;因此,我不认为这是与基于 Web 的代码(即框架、URL 欺骗)有关的问题。
但是,我无法确认这一点,因为它是基于 Web 的 PHP/JS 脚本。
看来,当第一次加载https://myweb.comWKWebView 时,代码也没有检测到初始重定向到https://myweb.com/dashboard. 只有上面提到的两条观察者线似乎检测到了这种重定向。
我能够使用observerValue函数代码将确切的URL值打印到控制台:
if let key = change?[NSKeyValueChangeKey.newKey] {
print("URL: \(key)") // url value
}
Run Code Online (Sandbox Code Playgroud)
但是,我无法将其转换为字符串,无法将值分配给变量或将其传递给另一个函数。有没有办法将此键设置为变量.contains("https://")?启动时,键值 = 0,但之后,该值 = 所需的 URL(https://myweb.com/dashboard和https://myweb.com/dashboard/project/new)。
此解决方案使用较旧的 KVO 方法来实现与 @Rudedog 相同的结果,但有更多的包袱(即,您仍然需要移除观察者并处理独立的键路径)。有关更现代的解决方案,请参阅下面的@Rudedog 的回答。
我能够将 KVO 分配给WKWebView.urlString 变量。从那里,我能够将 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
}
}
Run Code Online (Sandbox Code Playgroud)
在你继续之前,我强烈建议你使用现代的 Swift 观察方法:
var webViewURLObserver: NSKeyValueObservation?
override func viewDidLoad() {
// ...
webViewURLObserver = webview.observe(\.url, options: .new) { webview, change in
print("URL: \(String(describing: change.newValue))")
// The webview parameter is the webview whose url changed
// The change parameter is a NSKeyvalueObservedChange
// n.b.: you don't have to deregister the observation;
// this is handled automatically when webViewURLObserver is dealloced.
}
}
Run Code Online (Sandbox Code Playgroud)
这样做可以使您的代码在调试问题时更清晰,更容易推理。
| 归档时间: |
|
| 查看次数: |
1480 次 |
| 最近记录: |