xamarin.forms - Xamarin Forms:自定义 webview 在 IOS 中不起作用
问题描述
我正在使用自定义 Webview 来解决ITMS-90809: Deprecated API Usage - Apple will stop accepting submissions of apps that use UIWebView APIs.
和解析HTML 数据。
我的代码:
MyWebView.cs
using Xamarin.Forms;
namespace CustomWebview
{
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
using CustomWebview;
using CustomWebview.iOS;
using WebKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(MyWebView), typeof(MyWebViewRenderer))]
namespace CustomWebview.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)));
}
}
}
}
当我打开具有 MyWebView 的页面时,页面重定向到 Main.cs 并显示以下异常。
我在这里上传了一个示例项目。
解决方案
我发现在 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。
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == "Url")
{
Control.LoadHtmlString(Element.Url, null);
}
}
这个答案来自我的另一个XF 线程。
推荐阅读
- python - Python tkinter - ttk - bind - 用另一个替换按下的字符
- python - 如何在 Django 中创建预定的帖子?
- libgdx - 如何使用 Libgdx 从 TiledMapEditor 解析 TileMapObject?
- c - 如何动态分配结构数组并在其中分配数组?
- php - 如何从 php 触发批处理文件以及如何从 url 获取查询字符串并将其作为参数传递给批处理文件?
- node.js - 如何监控 Mongoose 连接池
- sql - 有没有办法比较 SQL 中的逗号分隔字段?
- precision - 计算不准确的任意精度?
- laravel - Redis ERR 未知命令“FLUSHDB”
- pdf - jpg到pdf的批量转换