Since webviewdidfinishload
has been deprecated and the webKit
delegates don't seem to trigger when navigating to another url
(from what I can see), I looked into using observer forKeyPath
, like here:
How can I detect when url of amp page changed with WKWebview
And while this seems like a valid approach, I can't get the observeValue
to trigger. At times it works, but most often it doesn't, and there doesn't seem to be any consistency.
- (void)setUpWebView {
NSString * urlString = [NSString stringWithFormat:@"www.thisisnottherealurl.com"];
NSURL *url = [NSURL URLWithString: urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
WKWebViewConfiguration *webViewConfig = [WKWebViewConfiguration new];
_webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webViewConfig];
_webView.navigationDelegate = self;
_webView.translatesAutoresizingMaskIntoConstraints = NO;
_webView.alpha = 0.0f;
// _webView.alpha = 1;
[_webViewContainer addSubview:_webView];
[self startLoadingAnimation];
[_webView.topAnchor constraintEqualToAnchor:_webViewContainer.topAnchor].active = YES;
[_webView.bottomAnchor constraintEqualToAnchor:_webViewContainer.bottomAnchor].active = YES;
[_webView.rightAnchor constraintEqualToAnchor:_webViewContainer.rightAnchor].active = YES;
[_webView.leftAnchor constraintEqualToAnchor:_webViewContainer.leftAnchor].active = YES;
[_webView.heightAnchor constraintEqualToAnchor:_webViewContainer.heightAnchor].active = YES;
[_webView loadRequest:request];
//IMPORTANT PART
[_webView addObserver:self forKeyPath:@"url" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld | NSKeyValueObservingOptionPrior context:nil];
}
And then the observeValue
part:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"OBSERVED");
}
Now, this doesn't trigger. Instead of observing _webView
I have also tried _webView.URL.absoluteString
. But still, it doesn't trigger. I have added alternative options like so: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld | NSKeyValueObservingOptionPrior
but still nothing.
What am I doing wrong?
Is there a better approach to this? Is there a delegate
that actually trigger when navigating to another url link?