由于webviewdidfinishload
已被弃用,并且webKit
代理在导航到另一个url
时似乎没有触发(从我的看到,所以我使用观察器forKeyPath
进行了调查,如下所示:
How can I detect when url of amp page changed with WKWebview
虽然这似乎是一种有效的方法,但我无法触发observeValue
。有时它可以工作,但大多数情况下不起作用,而且似乎没有任何一致性。
- (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];
}
然后是observeValue
部分:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"🤩OBSERVED");
}
现在,这不会触发。除了观察_webView
,我还尝试了_webView.URL.absoluteString
。但是,它不会触发。我添加了其他替代选项,例如:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld | NSKeyValueObservingOptionPrior
,但仍然没有。
我在做什么错?
是否有更好的方法?导航到另一个URL链接时是否实际触发delegate
?
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
NSURLRequest* request = navigationAction.request;
if ([request.URL.urlString hasPrefix:@<Do ur checking here>])
{
decisionHandler(WKNavigationActionPolicyCancel); // Cancel the request
}
else
{
decisionHandler(WKNavigationActionPolicyAllow); // Allow the request.
}