使用LoadFileUrl加载本地内容的WKWebView

3
我正在尝试使用LoadFileUrl方法在WKWebView中加载本地html文件,但是我得到的是一个空白视图。这是一个Xamarin.Mac应用程序(尚未有沙盒)。
WKWebViewConfiguration conf = new WKWebViewConfiguration();
WKWebView www = new WKWebView (View.Frame, conf);
View = www;

string index = Path.Combine (NSBundle.MainBundle.BundlePath, "WebApp/Index.html");
string webAppFolder = Path.Combine (NSBundle.MainBundle.BundlePath, "WebApp");

www.LoadFileUrl (new NSUrl ("file://"+index), new NSUrl ("file://"+webAppFolder));

"LoadRequest"可以很好地从远程服务器加载网页。

"Index.html"文件的构建操作为"BundleResource"。

感谢您的所有帮助!


https://dev59.com/92Af5IYBdhLWcg3wOQi2 - Gusman
@Gusman 谢谢,但我已经看到了链接,如果我理解正确,“LoadFileUrl”应该是解决方案,但它不起作用! 难道在ElCapitan上仍然有错误吗?我应该将html文件复制到“temp”文件夹中,然后从那里加载它吗? - frenchfaso
它应该加载,最好查看Webview检查器并查看加载时是否有任何错误:https://dev59.com/Tl8e5IYBdhLWcg3w7-Jz - Gusman
2个回答

5

对于那些不使用Xamarin并为loadFileURL:而奋斗数小时的人(就像我一样)。

当您将Web文件夹移动到项目中时,请选择“创建文件夹引用”。

输入图像描述

然后使用类似于以下代码的内容:

if let filePath = NSBundle.mainBundle().resourcePath?.stringByAppendingString("/WebApp/index.html"){
  let url = NSURL(fileURLWithPath: filePath)
  if let webAppPath = NSBundle.mainBundle().resourcePath?.stringByAppendingString("/WebApp") {
    let webAppUrl = NSURL(fileURLWithPath: webAppPath, isDirectory: true)
    webView.loadFileURL(url, allowingReadAccessToURL: webAppUrl)
  }
}

在html文件中使用像这样的文件路径。
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

不要像这样

<link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">

示例目录 在此输入图片描述


谢谢!您提供的示例代码和截图帮助我解决了一个问题。 - rams

3
克里斯·哈蒙斯在Xamarin论坛上为我指明了正确的方向。只需进行以下更改:
string index = Path.Combine (NSBundle.MainBundle.BundlePath, "WebApp/Index.html");
string webAppFolder = Path.Combine (NSBundle.MainBundle.BundlePath, "WebApp");

to

string index = Path.Combine (NSBundle.MainBundle.ResourcePath, "WebApp/Index.html");
string webAppFolder = Path.Combine (NSBundle.MainBundle.ResourcePath, "WebApp");

做到了!

1
你可以将你的答案选择为解决方案 :-) - testing

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接