You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI WebView在iOS上无法加载本地页面的解决方法

MAUI iOS WebView显示空白问题修复方案

问题描述

我正在给MAUI应用适配iOS平台,但WebView加载本地HTML时出现问题:Android端能正常显示内容,iOS端却只显示空白页。试过自定义iOS Handler但没用,求修复方法。

相关代码

NewsArticle.xaml

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:testApp="clr-namespace:TestApp"
             Loaded="PageLoaded"
             x:DataType="testApp:NewsArticleViewModel"
             x:Class="TestApp.NewsArticle">
    <Grid
            x:Name="NewsScrollView">
        <WebView
                IsVisible="true"
                Navigating="WebView_Navigating">
            <WebView.Source>
                <HtmlWebViewSource Html="{Binding ArticleContent}"/>
            </WebView.Source>
        </WebView>
    </Grid>
</ContentPage>

后台代码(NewsArticle.xaml.cs)

public partial class NewsArticle : ContentPage
{
    public readonly NewsArticleViewModel ViewModel;
    public NewsArticle(NewsArticleViewModel viewModel)
    {
        ViewModel = viewModel;
        BindingContext = viewModel;
        InitializeComponent();
        if (DeviceInfo.Platform == DevicePlatform.WinUI)
        {
            NewsScrollView.MaximumHeightRequest = 750;
        }
        else
        {
            NewsScrollView.MaximumHeightRequest = DeviceDisplay.MainDisplayInfo.Height / DeviceDisplay.MainDisplayInfo.Density * 0.6;
        }
    }
    protected void PageLoaded(object sender, EventArgs e)
    {
        ((NewsArticleViewModel)ViewModel).GetSpecificNews();
    }

    private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
    {
        e.Cancel = true;
        ((NewsArticleViewModel)ViewModel).NavigateUsingDeviceBrowser(e.Url);
    }
}

ViewModel代码

using CommunityToolkit.Mvvm.ComponentModel;
using System.Text.RegularExpressions;

namespace TestApp
{
    public partial class NewsArticleViewModel : ObservableObject
    {
        [ObservableProperty] private string _articleContent;
        [ObservableProperty] private string _article;

        public NewsArticleViewModel()
        {
        }

        public void GetSpecificNews()
        {
            Article = "<p></p><p>What is Lorem Ipsum?<span></span></p><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>";

            if (DeviceInfo.Current.Platform == DevicePlatform.WinUI)
                ArticleContent = "Not Available on windows";
            else
            {
                var appTheme = Application.Current.RequestedTheme;
                var textColor = appTheme == AppTheme.Light ? "#000000" : "#FBF9F9";

                ArticleContent = $@"<HTML><head><meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1' /><style>p{{color:{textColor}}} a{{color:#408F70}} ul li span{{color:{textColor} !important}} ul li a{{color:#408F70 !important}} img{{display: inline;height: auto;max-width: 100%;}} video{{display: inline;height: auto;max-width: 100%; allowfullscreen: true;}}</style></head><BODY>{ToBasicHtml(Article)}</BODY></HTML>";
            }
        }

        public string ToBasicHtml(string url)
        {
            if (string.IsNullOrEmpty(url))
                return "";
            return Regex.Replace(url, "<img(.*?)>", "<img $1 />");
        }

        public async void NavigateUsingDeviceBrowser(string url)
        {
            try
            {
                var uri = new Uri(url);
                await Browser.Default.OpenAsync(uri, BrowserLaunchMode.External);
            }
            catch (Exception ex)
            {
                return;
            }
        }
    }
}

修复方案

以下是几个针对性的修复步骤,按顺序尝试:

  1. 修正WebView布局约束
    iOS的WebView对布局尺寸要求更严格,当前Grid没有明确的行定义,导致WebView可能没有获得有效显示空间。修改XAML中的Grid:

    <Grid x:Name="NewsScrollView">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <WebView 
            Grid.Row="0"
            x:Name="MyWebView"
            IsVisible="true"
            Navigating="WebView_Navigating">
            <WebView.Source>
                <HtmlWebViewSource Html="{Binding ArticleContent}"/>
            </WebView.Source>
        </WebView>
    </Grid>
    

    给WebView加上Grid.Row="0"并指定行高为*,确保它占满Grid的可用空间。

  2. 异步延迟加载HTML内容
    iOS的UI初始化节奏和Android不同,直接在PageLoaded同步赋值可能导致WebView还没初始化完成。修改ViewModel和后台代码:

    • ViewModel中把GetSpecificNews改为异步方法:
      public async Task GetSpecificNews()
      {
          Article = "<p></p><p>What is Lorem Ipsum?<span></span></p><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>";
      
          if (DeviceInfo.Current.Platform == DevicePlatform.WinUI)
              ArticleContent = "Not Available on windows";
          else
          {
              var appTheme = Application.Current.RequestedTheme;
              var textColor = appTheme == AppTheme.Light ? "#000000" : "#FBF9F9";
      
              // 延迟100ms,给WebView初始化留时间
              await Task.Delay(100);
              ArticleContent = $@"<HTML><head><meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1' /><style>p{{color:{textColor}}} a{{color:#408F70}} ul li span{{color:{textColor} !important}} ul li a{{color:#408F70 !important}} img{{display: inline;height: auto;max-width: 100%;}} video{{display: inline;height: auto;max-width: 100%; allowfullscreen: true;}}</style></head><BODY>{ToBasicHtml(Article)}</BODY></HTML>";
          }
      }
      
    • 后台PageLoaded改为异步调用:
      protected async void PageLoaded(object sender, EventArgs e)
      {
          await ViewModel.GetSpecificNews();
      }
      
  3. 简化HTML内容排查问题
    先排除HTML格式问题,把ArticleContent替换成最基础的HTML测试:

    ArticleContent = "<html><body><h1>测试内容</h1><p>这是iOS WebView测试文本</p></body></html>";
    

    如果能正常显示,再逐步添加原来的样式和内容,定位是否是样式或特殊字符导致的问题。

  4. 直接赋值WebView.Source而非绑定
    有时候MAUI的绑定在iOS上可能存在延迟,尝试直接在后台给WebView赋值:

    protected async void PageLoaded(object sender, EventArgs e)
    {
        await ViewModel.GetSpecificNews();
        var htmlSource = new HtmlWebViewSource();
        htmlSource.Html = ViewModel.ArticleContent;
        MyWebView.Source = htmlSource;
    }
    

    记得给WebView加上x:Name="MyWebView"(步骤1中已添加)。

内容的提问来源于stack exchange,提问作者Vasile Mihai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 01:03:10