问题
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