1、加载本地沙盒路径时
if ([_localHtml5FilePath.absoluteString hasPrefix:@"file://"])
{
[self.wkwebview loadFileURL:_localHtml5FilePath allowingReadAccessToURL:[NSURL URLWithString:[_localHtml5FilePath.absoluteString stringByDeletingLastPathComponent]]];
}
else
{
NSURLRequest *request = [NSURLRequest requestWithURL:_localHtml5FilePath];
[self.wkwebview loadRequest:request];
}
2、路径加载出来后,一直不显示,白屏:
https://www.jianshu.com/p/af81a92b2243
解决方案:
loadFileURL: allowingReadAccessToURL:
第二个参数路径一定要弄对,即沙盒路径+HTML所在文件夹名称。
WKWebView 初始化时对 WKWebViewConfiguration 中 preferences 相关属性进行设置;
//不通过用户交互,是否可以打开窗口
configuration.preferences.javaScriptCanOpenWindowsAutomatically = true;
//是否支持JavaScript
configuration.preferences.javaScriptEnabled = true;
[configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
加载本地HTML
NSURL *fileURL = [NSURL fileURLWithPath:dirPath];
NSString *accessPath = [documentsPath stringByAppendingPathComponent:@"HTML所在文件夹名称"];
NSURL *accessURL = [NSURL fileURLWithPath:accessPath];
[self.webView loadFileURL:fileURL allowingReadAccessToURL:accessURL];
以上,本地HTML加载成功;
3、解决跨域问题:
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
[self registerAllJavascriptWithUserContent:userContentController];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.userContentController = userContentController;
config.preferences.javaScriptEnabled = YES;
config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
config.suppressesIncrementalRendering = YES; // 是否支持记忆读取
[config.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
if (@available(iOS 10.0, *)) {
[config setValue:@YES forKey:@"allowUniversalAccessFromFileURLs"];
}
重点是
if (@available(iOS 10.0, *)) {
[config setValue:@YES forKey:@"allowUniversalAccessFromFileURLs"];
}
4、wkwebview在使用过程中,会遇到数据拿不到的问题,这个时候很有可能是异步加载的问题,就是在js-oc交互数据时有一个先后问题,导致数据没有拿到,会造成白屏或其他现象。(解决方式,js里接收数据时加settimeout延迟函数或者在oc中采用第三种方法:https://blog.csdn.net/FlyingKuiKui/article/details/98619845
)
网友评论