我正在使用 webview 来解析我的 HTML 数据。为此,我使用自定义渲染。
在主项目中:
public class MyWebView : WebView
{
public static readonly BindableProperty UrlProperty = BindableProperty.Create(
propertyName: "Url",
returnType: typeof(string),
declaringType: typeof(MyWebView),
defaultValue: default(string));
public string Url
{
get { return (string)GetValue(UrlProperty); }
set { SetValue(UrlProperty, value); }
}
}
Ios 渲染器
public class MyWebViewRenderer : ViewRenderer<MyWebView, WKWebView>
{
WKWebView _wkWebView;
protected override void OnElementChanged(ElementChangedEventArgs<MyWebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var config = new WKWebViewConfiguration();
_wkWebView = new WKWebView(Frame, config);
SetNativeControl(_wkWebView);
}
if (e.NewElement != null)
{
Control.LoadHtmlString(Element.Url, null); //use this code instead
//Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Url)));
}
}
}
在 XAML 和 XAML.cs 中:
<local:MyWebView
x:Name="web_view"
VerticalOptions="FillAndExpand"/>
web_view.Url = htmldata;
但是我在运行项目时得到了
System.ArgumentNullException
。
截图:
WebViewRenderer always 显示
Hello world
(如果没有应用样式,则非常小):
//'WebViewRenderer' is obsolete: 'WebViewRenderer is obsolete as of 4.4.0. Please use the WkWebViewRenderer instead'
//WkWebViewRenderer inherits from WKWebView
public class MyWebViewRenderer : WkWebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var myWebView = (MyWebView)e.NewElement;
if (myWebView != null)
{
...
}
WKWebView wkWebView = this;
var htmlString = "<html><body>Hello world</body></html>";
wkWebView.LoadHtmlString(htmlString, null);
...
我认为 LoadHtmlString 方法是导致异常的原因,现在它说它是一个 ArgumentNullException,即不应该为 null 的参数为 null,并且为了修复您不应该在 WkWebView 中传递 null 的问题。您只需传递 NSBundle 的 MainBundle BaseUrl 即可,如下所示:
Control.LoadHtmlString(new NSString(Element?.Url), NSBundle.MainBundle.BundleUrl);
如果问题仍然存在,请确保在问题中添加 StackTrace。
此外,如果您有 XF 4.4 及更高版本,则可以使用
WkWebViewRenderer
。
从我的XF线程得到答案,将其发布在这里。示例项目也上传到那里。
我发现您在 Forms 项目中使用了 .Net Framework 库,请删除它并使用 .Net Standard HttpClient。 其次,尝试禁用您的某些 URL 的 ATS,例如:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>services.catholicbrain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
最后,将加载 URL 代码移至 OnElementPropertyChanged,就像 @Graverobber 所说:
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == "Url")
{
Control.LoadHtmlString(Element.Url, null);
}
}