frenchfaso
frenchfaso

Reputation: 491

WKWebView load local content with LoadFileUrl

I'm trying to load a local html file in a WKWebView with the LoadFileUrl method, but all I get is a blank view. It's a Xamarin.Mac App (no Sandbox yet).

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));

Loading a webpage from a remote server with "LoadRequest" works just fine.

Build Action for the "Index.html" file is "BundleResource"

Thanks for all your help!

Upvotes: 3

Views: 4168

Answers (2)

Koodimetsa
Koodimetsa

Reputation: 880

For those not using Xamarin and fighting with loadFileURL: for hours(like me).

When you are moving the web folder to a project, select "Create folder references"

enter image description here

Then use code that is something like this:

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)
  }
}

In the html file use filepath like this

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

not like this

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

Example directory enter image description here

Upvotes: 5

frenchfaso
frenchfaso

Reputation: 491

Chris Hamons pointed me in the right direction on the Xamarin forums. Just changing

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");

did the trick!

Upvotes: 3

Related Questions