为什么不在我的webView中观察ValueForKeyPath触发器?

问题描述 投票:0回答:1

由于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

ios objective-c webview webkit observers
1个回答
0
投票
- (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. }
© www.soinside.com 2019 - 2024. All rights reserved.