我正在尝试为WKWebview的加载/加载时间添加观察者,但仅在加载时才触发。它永远不会在加载时触发。我在做什么错?
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://google.com")!
let request = URLRequest(url:url)
self.webView.load(request)
self.webView.addObserver(self, forKeyPath: #keyPath(WKWebView.isLoading), options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "loading"{
if webView.isLoading{
print("loading")
}
else{
print("done")
}
}
}
您必须添加观察之前带有Web视图和KVO中关键路径的任何操作都是字符串,例如
override func viewDidLoad() {
super.viewDidLoad()
self.webView.addObserver(self, forKeyPath: "isLoading",
options: [.new], context: nil)
let url = URL(string: "https://google.com")!
let request = URLRequest(url:url)
self.webView.load(request)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "isLoading"{
if webView.isLoading{
print("loading")
}
else{
print("done")
}
}
}