WKWebView 加載本地文件
如果代碼在mainbundle里面粒竖,直接使用
loadRequest:[NSURL fileWithPath:]
即可如果代碼在文件系統(tǒng)氧骤,比如
cache/dist/index.html
呻疹,直接使用loadFileURL:fileUrl allowingReadAccessToURL:[NSURL fileWithPath:]
即可如果代碼在文件系統(tǒng),比如
cache/dist/index.html
筹陵,而且使用hash路由刽锤,最終訪問的路徑為cache/dist/index.html?#/router
,這時候使用第二種會直接返回錯誤, 使用NSURL fileURLWithPath: relativeToURL:
也是錯誤
對于第三種訪問
使用 file://朦佩,然后使用 URLWithString:
如下
NSString *htmlPath = [NSString stringWithFormat:@"file://%@/index.html?#/login", targetFilePath];
NSURL *fileUrl = [NSURL URLWithString:htmlPath];
NSURL *accessUrl = [NSURL fileURLWithPath:targetFilePath];
[webView loadFileURL:fileUrl allowingReadAccessToURL:accessUrl];
完整示例
整體邏輯: 把mainbundle里面的 dist.bundle內(nèi)容 拷貝到Cache/bundle/target.bundle并思,然后訪問 Cache/bundle/target.bundle/index.html?#/login
//拷貝dist.bundle到cache file里面的bundle文件下target.bundle
NSString* bundleOriginPath = [[NSBundle mainBundle] pathForResource:@"dist" ofType:@"bundle"];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *bundlePath = [path stringByAppendingString:@"/bundle"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:bundlePath]){
[fileManager createDirectoryAtPath:bundlePath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString * targetFilePath = [NSString stringWithFormat:@"%@/target.bundle", bundlePath];
NSError *error;
[fileManager removeItemAtPath:targetFilePath error:&error];//移除目標(biāo)目錄下該文件
NSError *error1;
[fileManager copyItemAtURL:[NSURL fileURLWithPath:bundleOriginPath] toURL:[NSURL fileURLWithPath:targetFilePath] error:&error1];
// 請求本地路徑
NSString *htmlPath = [NSString stringWithFormat:@"file://%@/index.html?#/login", targetFilePath];
WKWebView *webView = [[WKWebView alloc]initWithFrame:self.view.bounds];
NSURL *fileUrl = [NSURL URLWithString:htmlPath];
NSURL *accessUrl = [NSURL fileURLWithPath:targetFilePath];
[webView loadFileURL:fileUrl allowingReadAccessToURL:accessUrl];
[self.view addSubview:view];
寫在最后: 最后這個方法為什么能用,猜測是NSURL URLWithString對hash做了處理吕粗,但是fileURLWithPath并未處理纺荧。具體可以找大佬問問
demo自己實現(xiàn)去