美文网首页
Sandbox & WKWebView loadFileURL(

Sandbox & WKWebView loadFileURL(

作者: 千年一梦s | 来源:发表于2019-08-09 14:30 被阅读0次

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

    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=<WKReloadFrameErrorRecoveryAttempter: 0x2836af1c0>}
    

    经过搜索验证发现,猜测这是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(

          本文链接:https://www.haomeiwen.com/subject/whqhjctx.html