美文网首页
使用WKWebView的一些注意事项

使用WKWebView的一些注意事项

作者: 云天涯丶 | 来源:发表于2018-05-11 11:05 被阅读696次

最近在项目里使用WKWebView碰到的一些问题,在这里跟大家分享下经验。

1、修改userAgent

// 修改userAgent 不管iOS9以上还是以下都可以
- (void)webviewSetUserAgent{
    
    UIWebView *webView = [UIWebView new];
    NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *newAgent = [oldAgent stringByAppendingString:@"你需要添加的String"];
    NSDictionary *dict = @{@"UserAgent":newAgent};
    [[NSUserDefaults standardUserDefaults] registerDefaults:dict];
}

2、禁止长按出现菜单

    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    // 禁止长按出现菜单
    NSString *source = @"var style = document.createElement('style'); \
    style.type = 'text/css'; \
    style.innerText = '*:not(input):not(textarea) { -webkit-user-select: none; -webkit-touch-callout: none; }'; \
    var head = document.getElementsByTagName('head')[0];\
    head.appendChild(style);";
    WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [userContentController addUserScript:script];

3、禁止放大缩小

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    // 禁止放大缩小
    NSString *js = @"var script = document.createElement('meta');"
    "script.name = 'viewport';"
    "script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    [webView evaluateJavaScript:js completionHandler:nil];
}

4、webview加载h5打开微信、支付宝客户端并返回app

这里需要向微信申请h5支付,并设置一些参数
常见的问题看这里

// webview加载url(微信、支付宝)
NSMutableURLRequest *request;
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
// xxxx是自己设置的app URL Scheme
[request setValue:@"xxxx://" forHTTPHeaderField:@"Referer"];
[self.webView loadRequest:request];




- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{

    if ([navigationAction.request.URL.absoluteString containsString:@"weixin://"]) {// 微信
        decisionHandler(WKNavigationActionPolicyCancel);
        [self cancelClick];//回到选项页
        // wkwebview要这样解决
         [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
 
        }
    } else if ([navigationAction.request.URL.absoluteString containsString:@"alipay://"]){// 支付宝
        decisionHandler(WKNavigationActionPolicyCancel);

// 支付宝这里是URLDecode编码了,解码后发现有个参数fromAppUrlScheme:alipays,将alipays换成自己的app URL Scheme
        NSString *decodedString = [self URLDecodedString:navigationAction.request.URL.absoluteString];
        if ([decodedString containsString:@"fromAppUrlScheme"]) {
// 去掉alipay://alipayclient/?前缀,因为后面编码会导致错误(这里先去掉,编码后在加上)
            NSString *subStr = [decodedString stringByReplacingOccurrencesOfString:@"alipay://alipayclient/?" withString:@""];
// xxxx是自己设置的app URL Scheme
            NSString *repStr = [subStr stringByReplacingOccurrencesOfString:@"alipays" withString:@"xxxx"];
            NSString *encodedString = [NSString stringWithFormat:@"alipay://alipayclient/?%@",[self URLEncodedString:repStr]];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:encodedString]];
       
            }
        } else {
            [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
      
            }
        }
        
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}


// 编码
- (NSString *)URLEncodedString:(NSString *)str{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)str,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}

// 解码
- (NSString *)URLDecodedString:(NSString *)str{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}

参考:https://www.jianshu.com/p/90db7dfb075c

相关文章

网友评论

      本文标题:使用WKWebView的一些注意事项

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