首页 > 解决方案 > iOS:如何在 WKWebView 中加载本地文件(不在包中)?

问题描述

我想使用 WKWebView(不是 UIWebView)并在其中加载一些 html 文件。我准确地说我在 info.plist 中将 ArbitraryLoads 设置为 YES。

(有关信息,它适用于模拟器但不适用于设备)。

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

这是我的代码:

       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

提前致谢。

标签: iosobjective-cnsurlconnectionwkwebviewnsurlrequest

解决方案


您必须使用目录的根目录才能允许 webview 读取文件

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

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

推荐阅读