提供几种思路 wk要拿本地资源图片举例
- 第一种 设置WKWeb可访问相对路径(iOS 9之后且最好资源本地化)
[self loadFileURL:htmlURL allowingReadAccessToURL:AccessUrl];
//第一个参数为html的url地址,第二个为可以获取资源的辅助地址,这个路径包含html资源和媒体资源就可都访问到
第二种 沙盒
WKWeb通过路径去访问沙盒图片,除了temp可以被访问其他访问不了(尽量用真机去调试),不是很必要的资源可以这么做第三种 通过拦截协议做替换
// 注入
[NSURLProtocol registerClass:[WKURLProtocol class]];
//UIWeb就需上面一句代码 WKweb要使用到如下
Class cls = NSClassFromString(@"WKBrowsingContextController");
SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
if([(id)cls respondsToSelector:sel]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
[(id)cls performSelector:sel withObject:@"myapp"];
#pragma clang diagnostic pop
//上述调用了私有方法可能悲剧,app开发可以尝试加密拼接运行时等等,去尝试绕开
#import <Foundation/Foundation.h>
@interface WKURLProtocol : NSURLProtocol
{
NSURLRequest *request;
}
+ (BOOL)canInitWithRequest:(NSURLRequest *)theRequest;
@end
#import "WKURLProtocol.h"
@implementation WKURLProtocol
//都是重写的系统方法
+ (BOOL)canInitWithRequest:(NSURLRequest *)theRequest
{
//判断是否是特定协议,从而进行后面的调用操作
if ([theRequest.URL.scheme caseInsensitiveCompare:@"myapp"] == NSOrderedSame) {
return YES;
}
return NO;
}
+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest *)theRequest
{
return theRequest;
}
- (void)startLoading
{
//在此方法中做资源替换
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
MIMEType:@"image/png"
expectedContentLength:-1
textEncodingName:nil];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image1" ofType:@"png"];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[[self client] URLProtocol:self didLoadData:data];
[[self client] URLProtocolDidFinishLoading:self];
NSLog(@"start loading !");
}
- (void)stopLoading
{
NSLog(@"something went wrong!");
}
@end
- 第四种 base64 存数据库 或者 文件
data:image/jpeg;base64/base64字符串
- 第五种 开启一个本地webServer
gayhub - 第六种 下载远程url的Html
[wkwebView loadHTMLString:htmlString baseURL: 资源关联地址];
- PS: es6 未转 也会造成低版本加载不出本地文件
道阻且长,表面向阳