提供幾種思路 wk要拿本地資源圖片舉例
- 第一種 設置WKWeb可訪問相對路徑(iOS 9之后且最好資源本地化)
[self loadFileURL:htmlURL allowingReadAccessToURL:AccessUrl];
//第一個參數為html的url地址,第二個為可以獲取資源的輔助地址,這個路徑包含html資源和媒體資源就可都訪問到
第二種 沙盒
WKWeb通過路徑去訪問沙盒圖片,除了temp可以被訪問其他訪問不了(盡量用真機去調試),不是很必要的資源可以這么做第三種 通過攔截協(xié)議做替換
// 注入
[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開發(fā)可以嘗試加密拼接運行時等等,去嘗試繞開
#import <Foundation/Foundation.h>
@interface WKURLProtocol : NSURLProtocol
{
NSURLRequest *request;
}
+ (BOOL)canInitWithRequest:(NSURLRequest *)theRequest;
@end
#import "WKURLProtocol.h"
@implementation WKURLProtocol
//都是重寫的系統(tǒng)方法
+ (BOOL)canInitWithRequest:(NSURLRequest *)theRequest
{
//判斷是否是特定協(xié)議,從而進行后面的調用操作
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 未轉 也會造成低版本加載不出本地文件
道阻且長,表面向陽