Xamarin - Documentation

iOS

change platform

  1. Xamarin
  2. iOS
  3. Recipes
  4. Content Controls
  5. Web View
  6. Load Local Content

Load Local Content

Table of contents

This recipe shows how to load a local web page in a UIWebView control.

Sample Code:

Load Local Content.zip

Related Apple Documentation:

UIWebView Class Reference

Using UIWebView to display select document types

Recipe

To show local Html content in a UIWebView:

  1. Add the content to your MonoTouch project. Remember to set the Build Action to Content for all files. This screenshot shows the sample project’s Content folder with Html, image and CSS files.
    WebView_sln.png
  1. Create a UIWebView and add it to a view:
webView = new UIWebView (View.Bounds);
View.AddSubview(webView);
  1. Load the file using NSUrlRequest and NSUrl classes:
string fileName = "Content/Home.html"; // remember case-sensitive
string localHtmlUrl = Path.Combine (NSBundle.MainBundle.BundlePath, fileName);
webView.LoadRequest(new NSUrlRequest(new NSUrl(localHtmlUrl, false)));
webView.ScalesPageToFit = false;

Additional Information

Html generated in code can also be displayed, which is useful for customizing the content. To display an Html string, use the LoadHtmlString method instead of LoadRequest. Passing the path to the Content directory helps the web view resolve relative Urls in the Html, such as links, images, CSS, etc.

string contentDirectoryPath = Path.Combine (NSBundle.MainBundle.BundlePath, "Content/");
string html = "<html><a href='Home.html'>Click me</a></html>";
webView.LoadHtmlString(html, new NSUrl(contentDirectoryPath, true));