WKWebView loadFileURL throws WebPageProxy::Ignoring request to load this main resource because it is outside the sandbox

心不动则不痛 提交于 2020-06-17 01:47:26

问题


I am trying to open local html file in WKWebView, but I keep getting error message:

Received an unexpected URL from the web process: 'file:///Users/username/Library/Containers/dev.WebView/Data/file:/Users/username/Documents/WebView/WebView/WebView/WebContent/index.html'

2020-01-30 09:36:38.817862+0100 WebView[1679:20612] [Process] 0x101043e20 - WebPageProxy::Ignoring request to load this main resource because it is outside the sandbox

This is the code that I tried:

    NSString *path = @"file:///Users/username/Documents/WebView/WebView/WebView/WebContent/index.html";
    NSURL *url = [NSURL fileURLWithPath:path];

    [_webView loadFileURL:url allowingReadAccessToURL:url];

I have also tried allowing access to the Documents directory with:

    NSString *path = @"file:///Users/username/Documents/WebView/WebView/WebView/WebContent/index.html";
    NSURL *url = [NSURL fileURLWithPath:path];

    NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] objectAtIndex:0];
    [_webView loadFileURL:url allowingReadAccessToURL:documentsURL];

I have also enabled Outgoing Connections (Client) in Signing & Capabilities settings of the projects, does not help either.


回答1:


The solution is to add html file to project and bundle it with build so it shows up in Resources directory. In Build Phases settings of project, file needs to show up under Copy Bundle Resources.

This is the piece of code that can be used to load file:

    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *filePath = [mainBundle pathForResource:@"index" ofType:@"html"];

    NSURL *url = [NSURL fileURLWithPath:filePath];

    [_webView loadFileURL:url allowingReadAccessToURL:[url URLByDeletingLastPathComponent]];

You can also find complete solution on my github repository: Cocoa Web View Load Local File



来源:https://stackoverflow.com/questions/59982111/wkwebview-loadfileurl-throws-webpageproxyignoring-request-to-load-this-main-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!