使用WKWebView时遇到的一些坑

1.加载的html实际高度与展示出的高度不符(使用UIWebView时正常)

在头中加入

<head>
 <meta name="viewport" content="width=device-width,user-scalable=no, initial-scale=1">
</head>

2.参数太长使用POST加载网页时失败

使用下方代码请求失败

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];

暂未找到原因,替代方案为加载一段含有js请求的html,在加载完成后调用post方法

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<script type="text/javascript">
    function post(path,json){
        var method = "post";
        var form = document.createElement("form");
        form.setAttribute("method", method);
        form.setAttribute("action", path);
        

        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", "json");
        hiddenField.setAttribute("value", json);
        form.appendChild(hiddenField);

        document.body.appendChild(form);
        form.submit();
    }

</script>
</html>

3.使用URLRequest在请求头中加入cookie值无效

WKWebView不会再从NSHTTPCookieStorage取cookie,而是需要在初始化时通过WKUserScript写入

WKUserContentController* userContentController = WKUserContentController.new;
NSString *scriptStr = [NSString stringWithFormat:@"document.cookie = 'JSESSIONID=%@'",[IMClient shareClient].sessionId];
WKUserScript * cookieScript = [[WKUserScript alloc]
                               initWithSource:scriptStr
                               injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
webViewConfig.userContentController = userContentController;

[webViewConfig.userContentController addScriptMessageHandler:self name:@"nativeInteraction"];
WKWebView *webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:webViewConfig];
webView.scrollView.bounces = false;
webView.navigationDelegate = self;
[self.view addSubview:webView];
_webView = webView;

4.加载本地html时,css与图片无效

通常css及图片引用如下

<link href="css/login.css" rel="stylesheet" type="text/css" />
 background: url("../images/dc-bg.png") no-repeat;

去掉文件夹路径, 更改为下方格式即可

 <link href="login.css" rel="stylesheet" type="text/css" />
  background: url("dc-bg.png") no-repeat;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容