Load Local Content

PDF for offline use
Sample Code:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

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

Recipe

To show local Html content in a UIWebView:

  1. Add the files to your Xamarin.iOS project - in this example the HTML, images and style sheets have all been placed inside a Content folder in the project. Remember to set the Build Action to BundleResource for all files.

  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:
// Note the Content folder is where we placed the files
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.

// assumes you've placed all your files in a Content folder inside your app
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));

 

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.