Sandbox & WKWebView loadFileURL(_, allowingReadAccessTo:) Inconsistency

从沙盒加载网页和资源文件,第一次加载没问题,第二次加载的时候会加载失败报错

2019-08-09 14:20:23.284917+0800 MediaPlay[1041:1359144] ++++++++++file:///var/mobile/Containers/Data/Application/38666562-0E95-4EDF-A4C1-FF37C5465E29/Documents/unzip/52/index.html?currentTime=0
2019-08-09 14:20:23.308443+0800 MediaPlay[1041:1359144] 加载
失败 -- Error Domain=kCFErrorDomainCFNetwork Code=1 "(null)" 
UserInfo{_NSURLErrorFailingURLSessionTaskErrorKey=LocalData
Task <6B857B83-6193-45B9-BFE9-2E2E1C53A292>.<16>, 
_WKRecoveryAttempterErrorKey=}

经过搜索验证发现,猜测这是WKWebView的一个内部限制,会锁定第一次使用资源文件目录(allowingReadAccessTo)

To make a long story short, you have a allowingReadAccessToURL  
parameter in loadFileURL:allowingReadAccessToURL: method that 
tells WKWebView what are allowed paths when it loads a local file. 
From some reason, it doesn't care about this parameter when some 
page with a different allowingReadAccessToURL parameter is loaded.
 So I recommend to use the entire Documents path space as a default 
parameter to this method:
image.png
解决方法:将资源文件目录的范围扩大,能找到资源文件,就可以正常加载了
NSURL *documentsURL = [[[NSFileManager defaultManager] 
URLsForDirectory:NSDocumentDirectory 
inDomains:NSUserDomainMask] objectAtIndex:0];
[self loadFileURL:request.URL allowingReadAccessToURL:documentsURL];

或者

NSString *pathA = "file:///path/to/abc/dirA/A.html";
NSString *pathB = "file:///path/to/abc/dirB/B.html";
NSString *pathC = "file:///path/to/abc/dirC/C.html";


NSURL *url = [NSURL fileURLWithPath:pathA];

NSURL *readAccessToURL = [[url URLByDeletingLastPathComponent] URLByDeletingLastPathComponent];
 // readAccessToURL == "file:///path/to/abc/"

[self.wk_webview loadFileURL:url allowingReadAccessToURL:readAccessToURL];
// then you want load  pathB
url = [NSURL fileURLWithPath:pathB];
// this will work fine
[self.wk_webview loadFileURL:url allowingReadAccessToURL:readAccessToURL];

你可能感兴趣的:(Sandbox & WKWebView loadFileURL(_, allowingReadAccessTo:) Inconsistency)