WKWebView 使用整理

特别注意:在ios 9下必须设置这个,否则加载不了:

NSAppTransportSecurity
    
        NSAllowsArbitraryLoads
        
    

监听title

[self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"title"]) {
        if (![self.title isEqualToString:self.webView.title]) {
            self.title = self.webView.title;
        }
    }
}

- (void)dealloc
{
    [_webView removeObserver:self forKeyPath:@"title"];
}

处理WKWebView跳转,比如sechma:

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    decisionHandler(WKNavigationActionPolicyAllow);
    //(xxxxx://) schema协议
    if ([navigationAction.request.URL.absoluteString hasPrefix:@"xxxxx://"]) {
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
    }
}

清除缓存

if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        NSSet *websiteDataTypes = [NSSet setWithArray:@[WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache]];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            DLog(@"Clear WKWebView Cache");
        }];
    } else {
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    }

js的alert()弹窗处理

需要先实现WKUIDelegate这个代理
//uiwebview 中这个方法是私有方法 通过category可以拦截alert
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    
    //    NSLog(@"%s", __FUNCTION__);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 必须要实现,不然会crash
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
}

你可能感兴趣的:(WKWebView 使用整理)