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

1

0

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.

Occultism answered 23/10, 2018 at 12:23 Comment(0)
L
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];
Lunette answered 23/10, 2018 at 15:48 Comment(1)
Wow I could spend hours and hours on that... Thanks it works.Rb

© 2022 - 2024 — McMap. All rights reserved.