底辺SE奮闘記

年収300万SEブログ

【Xamarin】プロジェクト埋め込みのhtmlをWebViewに表示する

概要

docs.microsoft.com

こちらの通り作成しても一部うまくいかなかったため、なんとかする。

環境

  • Visual Studio for Mac 8.10.7
  • Xamarin.Essentials 1.6.1
  • Xamarin.Formas 5.0.0.2012

埋め込みファイルの場所

OS 保存場所 ビルドアクション
iOS Resources BundleResource
Android Assets AndroidAsset

下記ソースコードでは、上記保存場所にtest.htmlが保存されているものとします。

ソースコード

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="hoge.MainPage">
    <RelativeLayout>
        <WebView
            x:Name="webview"
            RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1}"
            RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=1}"
            >
        </WebView>
    </RelativeLayout>
</ContentPage>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace hoge
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            WebView webView = this.FindByName<WebView>("webview");

            var source = new UrlWebViewSource();
            source.Url = DependencyService.Get<IBaseUrl>().Get() + "test.html";

            webView.Source = source;
        }
    }
}

パス取得インタフェース/クラス

インタフェース

using System;
namespace hoge
{
    public interface IBaseUrl
    {
        string Get();
    }
}

クラス

iOS
using System;
using Foundation;
using Xamarin.Forms;

[assembly: Dependency(typeof (hoge.iOS.BaseUrl))]
namespace hoge.iOS
{
    public class BaseUrl :IBaseUrl
    {

        public string Get()
        {
            return NSBundle.MainBundle.BundlePath;
        }
    }
}
Android
using System;
using Xamarin.Forms;

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