美文网首页
WKWebView 使用整理

WKWebView 使用整理

作者: Minoz_min | 来源:发表于2017-01-18 12:03 被阅读65次

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

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

解决cookie同步问题

NSMutableDictionary *cookieDic = [[NSMutableDictionary alloc] init];
    NSMutableArray *domainArray = [[NSMutableArray alloc] init];
    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        [cookieDic setObject:cookie.value forKey:cookie.name];
        [domainArray addObject:cookie.domain];
    }
    
    // cookie重复,先放到字典进行去重,再进行拼接
    for (int i = 0; i < cookieDic.count; i++) {
        NSString *key = [[cookieDic allKeys] objectAtIndex:i];
        //垮域一定要加上domain,否则cookie不能同步
        NSString *appendString = [NSString stringWithFormat:@"document.cookie='%@=%@;%@=%@';", key, [cookieDic valueForKey:key], @"domain", domainArray[i]];
        [cookieValue appendString:appendString];
    }
    WKUserContentController* userContentController = WKUserContentController.new;
    WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:cookieValue injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    
    [userContentController addUserScript:cookieScript];
    WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
    webViewConfig.userContentController = userContentController;
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) configuration:webViewConfig];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    self.webView.backgroundColor = HSQColorBackgroundGrayLight;
    [self.view addSubview:self.webView];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];

监听title

[self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)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 使用整理

      本文链接:https://www.haomeiwen.com/subject/xkovbttx.html