Loading Local HTML with WebView Xamarin Forms

前端 未结 5 1105
离开以前
离开以前 2021-01-19 20:11

I am trying to load a local HTML page in a webview with Xamarin forms. I am using the basic example in the dev docs although I can get a URL to load I can\'t get my own HTML

5条回答
  •  無奈伤痛
    2021-01-19 20:33

    You must check the file properties for Build Action = BundleResource

    Try this code to load local html file

    var source = new HtmlWebViewSource();
            string url = DependencyService.Get().GetBaseUrl();
            string TempUrl = Path.Combine(url, "terms.html");
            source.BaseUrl = url;
            string html;
            try
            {
                using (var sr = new StreamReader(TempUrl))
                {
                    html = sr.ReadToEnd();
                    source.Html = html;
                }
            }
            catch(Exception ex){
                Console.WriteLine(ex.Message);
            }
    

    Implementations of the interface for each platform must then be provided

    iOS

    [assembly: Dependency(typeof(BaseUrl))]
    namespace yournamespace
    {
       public class BaseUrl: IBaseUrl
       {
          public string GetBaseUrl()
          {
            return NSBundle.MainBundle.BundlePath;
          }
       }
    }
    

    Android

    [assembly: Dependency (typeof(BaseUrl))]
     namespace yournamespace {
       public class BaseUrl_Android : IBaseUrl {
          public string Get() {
            return "file:///android_asset/";
         } 
       }
     }
    

提交回复
热议问题