SunAwtCanvas
SunAwtCanvas

Reputation: 1460

Xamarin - file:///android_asset

What my app does: Load index.html to WebView

index.html's Code:

<html>
<body>
<a href="Posts10.html"><h2>Interesting Stuff</h2></a>
</body>
</html>

So whenever I click on the link, It gives me this error:

enter image description here

index.html and Posts10.html are located in

Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"/CachedPosts"

a.k.a

"/data/user/0/com.companyname.theoctant/files/CachedPosts"

Upvotes: 1

Views: 1926

Answers (2)

SushiHangover
SushiHangover

Reputation: 74144

When there is an internet connection, the WebView opens a url. But if there isn't, it opens a html file. And Xamarin Forms

All you need to do is swap the type of WebViewSource that you are using and assign the proper properties to it wether you are connected or not.

So for a Forms' WebView, if you are "Internet" connected, create a UrlWebViewSource and assign the property Url, but if not, create a HtmlWebViewSource and assign the BaseUrl to either NSBundle.MainBundle.BundlePath or file:///android_asset/ for static app bundled resources, or your custom cache directory.

Something like this:

WebViewSource webViewSource;
if (InternetConnected)
{
    webViewSource = new UrlWebViewSource { Url = "https://stackoverflow.com" };
}
else
{
    string baseUrl = cacheDir;
    webViewSource = new HtmlWebViewSource { BaseUrl = baseUrl, Html = cachedHtml };
}
webView.Source = webViewSource;

Upvotes: 0

afilbert
afilbert

Reputation: 1540

This may help. From the Xamarin docs:

On Android, place HTML, CSS, and images in the Assets folder with build action AndroidAsset as demonstrated below:

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/webview?tabs=vswin#android

Upvotes: 2

Related Questions