iOS: How to load local files (not in the bundle) in a WKWebView?

喜欢而已 提交于 2019-12-13 05:29:06

问题


I would like to use a WKWebView (not a UIWebView) and load some html files in it. I precise that I put the ArbitraryLoads to YES in info.plist.

(For info, it works on simulator but not on device).

<key>NSAppTransportSecurity</key>
<dict>
      <key>NSAllowsArbitraryLoads</key>
        <true/>
</dict>

Here is my code:

       WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
    [theConfiguration setMediaPlaybackAllowsAirPlay:YES];
    [theConfiguration setAllowsInlineMediaPlayback:YES];
    [theConfiguration setAllowsPictureInPictureMediaPlayback:YES];
    [theConfiguration setAllowsAirPlayForMediaPlayback:YES];
       [theConfiguration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
[theConfiguration setValue:@YES forKey:@"_allowUniversalAccessFromFileURLs"];
       self.webView.navigationDelegate = self; 
       self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];

      NSURL *nsurl2 = [NSURL fileURLWithPath:[[[self documentsDirectory] stringByAppendingPathComponent:user_appli] stringByAppendingPathComponent:@"index.html"]];//locally


 [self.webView loadFileURL:nsurl2 allowingReadAccessToURL:nsurl2]; //=> doesn't work  

 [self.webView loadRequest:[NSURLRequest requestWithURL:nsurl2]]; //=> doesn't work

Thanks in advance.


回答1:


You have to use the root of the directory to allow the webview to read the file

NSURL *nsurl = [NSURL fileURLWithPath:[[[self documentsDirectory] stringByAppendingPathComponent:user_appli] stringByAppendingPathComponent:@"index.html"]]; //locally
NSURL *readAccessToURL = [[nsurl URLByDeletingLastPathComponent] URLByDeletingLastPathComponent];

[self.webView loadFileURL:nsurl allowingReadAccessToURL:readAccessToURL];


来源:https://stackoverflow.com/questions/52948999/ios-how-to-load-local-files-not-in-the-bundle-in-a-wkwebview

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