The goal here is to detect whenever the URL of the webView
changes. Since the didCommit
and didStartProvisionalNavigation
functions of the WKWebView class don't always seem to fire when working with certain elements within a WebView, I now have to add an observer to pick up when the WebView's URL value changes.
So far I have created my own Notification extension with name checkURL
:
Swift Progress
extension Notification.Name {
static let checkURL = Notification.Name("checkURL")
}
NotificationCenter.default.post(name: .checkURL, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(getter: webView.url), name: .checkURL, object: webView.url)
Objective-C Solution (KVO)
// Add an observer
[webView_ addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:NULL];
// Method that gets called when the URL value changes
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
// Code
}
How would I go about applying that Objective-C code to fire a function whenever the URL value changes? I am still trying to wrap my head around Notifications and how they work with object values, so any explanation would be very helpful as well!
Thank you for reading!
EDIT: Just to clear things up, I will reword my question:
Since the didCommit
and didStartProvisionalNavigation
don't always seem to fire (especially when working with JavaScript-based sites, as well as PHP – you'll constantly see URLs being changed with symbols such as #
and whatnot); however, as stated before, the built-in WKWebView functions don't seem to catch those. So what I am trying to do here is find a workaround to catch any sort of changes made to the URL, regardless of if it's just a #
, etc. And preferably keeping the code entirely Swift – as I am still learning. :)