美文网首页iOS点点滴滴
WKWebview使用记录

WKWebview使用记录

作者: 逆袭的小菜鸟 | 来源:发表于2018-04-04 16:06 被阅读59次

    1、WKWebview添加手势

    UISwipeGestureRecognizer *swipe =[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction)];
    swipe.delegate = self;
    [wkWebView addGestureRecognizer:swipe];
    
    // 允许多个手势并发
    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
        return YES;
    }
    

    2、WKWebview禁用弹簧滑动

    wkWebView.scrollView.bounces = NO;
    

    3、WKWebview被js调用

    window.webkit.messageHandlers.<对象名>.postMessage(body:<数据>)//body中可以直接放js对象,也可以省略body
    
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
    {
          NSLog(@"JS 调用了 %@ 方法,传回参数 %@",message.name,message.body);
          NSMutableDictionary *dic=[message.body objectForKey:@"body"];
    }
    

    4、WKWebview调用js

    NSData *data=[NSJSONSerialization dataWithJSONObject:self->object options:NSJSONWritingPrettyPrinted error:nil];
    NSString *dataJson=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        
    NSString *dataFunc=[NSString stringWithFormat:@"generalChart(%@,%lu)",dataJson,(unsigned long)self->chartType];
        
    [self evaluateJavaScript:dataFunc completionHandler:^(id _Nullable param, NSError * _Nullable error) {
            
    }];
    

    5、wkwebview手势返回抖屏问题:
    webview侧滑返回后会接着触发html页面添加的transition动画导致

     [wkWebView setAllowsBackForwardNavigationGestures:true];//设置手势返回
    

    6、wkwebview无法跳转App Store

    - (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler
    {
        WKNavigationActionPolicy policy =WKNavigationActionPolicyAllow;
        if([[navigationAction.request.URL host] isEqualToString:@"itunes.apple.com"] &&[[UIApplication sharedApplication] openURL:navigationAction.request.URL])
        {
            policy =WKNavigationActionPolicyCancel;
        }
       decisionHandler(policy);
    }
    

    wkwebview无法跳转企业安装

    - (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler
    {
        
         NSString *strRequest = [navigationAction.request.URL.absoluteString  stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        if ([strRequest containsString:@"itms-services"]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strRequest]];
        }
    
        decisionHandler(policy);
    }
    

    7、wkwebview监听事件

    [webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    // 进度条
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    // 只要观察的对象属性有新值就会调用
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
    {
        NSLog(@"%d, %d", self.webView.canGoForward, self.webView.canGoBack);
    }
    

    8、wkwebview关于iPhone X页面适配,全屏显示,发现顶部出现20px的空白
    添加启动图


    增加X启动图

    AppDelegate的didFinishLaunchingWithOptions方法中添加

     if (@available(iOS 11.0, *)) {
         [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
     }
    

    webview添加

    if (@available(iOS 11.0, *)) {
        wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    

    9、wkwebview无法加载沙盒中Doc下目录中html,需要放在tem
    从mainBundle拷贝文件夹到tem

        NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"dist" ofType:@""];
        NSString *path = NSTemporaryDirectory();
        NSString *cacheStr=[NSString stringWithFormat:@"%@/dist",path];
        NSFileManager * defaultManager = [NSFileManager defaultManager];
        NSError *err = nil;
        [defaultManager copyItemAtPath: strResourcesBundle toPath:cacheStr error: &err];
        if(err){
            NSLog(@"复制初始资源文件出错:%@", err);
        }
        
        NSArray *contensArr= [NSArray arrayWithArray:[defaultManager contentsOfDirectoryAtPath:cacheStr error:nil]];
        NSLog(@"%@",contensArr);
    

    wkwebview从tem目录下获取加载文件,生成url时使用fileURLWithPath

    NSString *cachesPath = NSTemporaryDirectory();//tem文件目录
    NSString *cacheStr=[NSString stringWithFormat:@"%@dist/index.html",cachesPath];
    NSURL *url=[NSURL fileURLWithPath: cacheStr];
    if (@available(iOS 9.0, *)) {
         [wkWebView loadFileURL:url allowingReadAccessToURL:url];
    } else {
         [wkWebView loadRequest:[NSURLRequest requestWithURL:url]];
    }
    

    获取沙盒地址的方法

    NSString *homeDir = NSHomeDirectory();// 获取沙盒主目录路径
    NSString *cachesPath = NSTemporaryDirectory();//tem文件目录
    NSString *cachesPath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];//Documents文件目录
    
    

    10、WKWebView加载不受信任的https造成错误:参考

    - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
        NSLog(@"didReceiveAuthenticationChallenge");
        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
            
            completionHandler(NSURLSessionAuthChallengeUseCredential,card);
    
        }
    }
    

    11、WKWebView隐藏导航栏全屏加载,导航无法手势返回问题,开始以为与setAllowsBackForwardNavigationGestures手势冲突造成,排查后发现是导航隐藏后不支持手势返回,添加以下代码即可,更详细问题参考文章第2点

    隐藏导航代码

    [self.navigationController setNavigationBarHidden:NO animated:NO];
    

    支持手势返回代码

        self.navigationController.interactivePopGestureRecognizer.delegate = self;
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    

    12、WKWebView设置setAllowsBackForwardNavigationGestures手势返回事件监听方法:

    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    -(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
      
        return YES;
    }
    

    13、WKWebView在iOS8中使用允许手势返回会报错

    if (@available(iOS 9.0, *)) {
       [wkWebView setAllowsBackForwardNavigationGestures:true];
    } 
    

    14、WKWebview在iOS11中的适配

    if (@available(iOS 11.0, *)) {
            wkWebView.scrollView.contentInsetAdjustmentBehavior =UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 11.0, *)) {
            [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    

    持续更新中...

    相关文章

      网友评论

        本文标题:WKWebview使用记录

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