问题:由
UIWebView切WKWebView后,HTML加载本地HTMLString时,图片无法显示。
WKWebView加强了安全性,不再允许跨域访问,所有跨域地址都失效了,包括不再同一文件夹下的CSS、JS等文件引用。
解决办法:
1、把
src中的图片单独读取出来,然后转成Data拼到src中。
2、移动图片存储到tmp中,加载本地Html时设置BaseURL即可(tmp会被定期清理,且无法兼容老版本,弃)
3、启动一个本地服务器,拥有一个读取沙盒的权利(推荐使用)
前面两种就不说了,直接说第三种
导入一个三方 GCDWebServer
自行import然后开启服务,可以写到页面的ViewDidLoad也可以全局写到AppDelegate
if ([self.contentWebView isKindOfClass:[WKWebView class]]) {
self.webSever = [[GCDWebServer alloc] init];
[self.webSever addGETHandlerForBasePath:@"/" directoryPath:NSHomeDirectory() indexFilename:nil cacheAge:3600 allowRangeRequests:YES];
[self.webSever startWithPort:80 bonjourName:nil];
}
在处理HTMLString的位置,进行地址替换。
if ([self.contentWebView isKindOfClass:[WKWebView class]]) {
//通过循环,替换掉所有Library路径
NSString *Library = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
while ([displayHtmlbody containsString:Library]) {
displayHtmlbody = [displayHtmlbody stringByReplacingOccurrencesOfString:Library withString:@"/Library"];//把library滤镜换成Library字符串,再拼接本地服务器地址。
displayHtmlbody = [displayHtmlbody stringByReplacingOccurrencesOfString:@"file://localhost" withString:@"http://localhost"];
}
}
关闭服务器(如果你需要单页面开启的话)
- (void)dealloc {
//停止本地服务
if ([self.contentWebView isKindOfClass:[WKWebView class]]) {
[self.webSever stop];
self.webSever = nil;
}
}








网友评论