【问题标题】:WKWebView load local content with LoadFileUrlWKWebView 使用 LoadFileUrl 加载本地内容
【发布时间】:2016-03-01 14:44:52
【问题描述】:

我正在尝试使用 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”

感谢您的帮助!

【问题讨论】:

  • @Gusman 谢谢,但我已经看到了链接,如果我没看错的话,“LoadFileUrl”应该是解决方案,但它不起作用! ElCapitan 上是否仍然存在问题?我应该将 html 文件复制到“temp”文件夹中并从那里加载吗?
  • 应该可以加载了,最好看看webview inspector,看看加载时有没有报错:stackoverflow.com/questions/25200116/…

标签: c# xamarin wkwebview xamarin.mac


【解决方案1】:

对于那些不使用 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">

示例目录

【讨论】:

  • 谢谢!您的示例代码和屏幕截图帮助我调试了我一直在寻找的问题。
【解决方案2】:

Chris Hamons 在Xamarin forums 上为我指明了正确的方向。 只是改变

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

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

成功了!

【讨论】:

  • 你可以选择你的答案作为解决方案然后:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
相关资源
最近更新 更多