Xamarin表格,PDF显示在iOS Simulator上,而不显示在真正的iPad

时间:2018-07-30 15:23:05

标签: xamarin xamarin.forms xamarin.ios wkwebview

我有一个自定义的Webview渲染器,以显示我从API调用中下载的PDF。我将PDF保存到本地存储,并通过自定义Webview渲染器显示。它在模拟器上可以正常工作,但是当我在真正的iPad上尝试时,页面仅显示空白(顶部的页面标题除外)。 这是要显示的自定义渲染代码。

using MyProject.Core.Controls;
using MyProject.Core.Helpers;
using MyProject.Core.Services.FileStorage;
using MyProject.iOS.Renderers;
using Foundation;
using WebKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(PDFWebViewer), typeof(PDFWebViewerRenderer))]
namespace MyProject.iOS.Renderers
{
    public class PDFWebViewerRenderer : ViewRenderer<PDFWebViewer, WKWebView>
    {
        PDFWebViewer WebViewer => Element as PDFWebViewer;

        WKUserContentController userController;

        protected async override void OnElementChanged(ElementChangedEventArgs<PDFWebViewer> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                userController = new WKUserContentController();

                var config = new WKWebViewConfiguration { UserContentController = userController };
                var webView = new WKWebView(Frame, config);
                SetNativeControl(webView);
            }
            if (e.OldElement != null)
            {
                userController.RemoveAllUserScripts();
                userController.Dispose();
                var webViewer = e.OldElement as PDFWebViewer;
            }
            if (e.NewElement != null)
            {
                //var customWebView = Element as CustomWebView;

                var filepath = await FileStorageService.FileExists(Constant.Agreement.AGREEMENT_PDF_PREVIEW);

                if (!string.IsNullOrEmpty(filepath))
                {
                    var request = new NSUrlRequest(new NSUrl($"file://" + filepath));
                    Control.LoadRequest(request);
                }
            }
        }
    }
}

在调试器中,我检查了这是文件路径/var/mobile/Containers/Data/Application/A9D74D50-7466-4F9E-8986-77F8305BD179/Documents/../Library/AGREEMENT_PREVIEW.pdf

这是它传递给Control.LoadRequest()的请求, file:///var/mobile/Containers/Data/Application/A9D74D50-7466-4F9E-8986-77F8305BD179/Documents/../Library/AGREEMENT_PREVIEW.pdf

1 个答案:

答案 0 :(得分:1)

找到了解决方案。由于某些原因,实际设备不喜欢Control.LoadRequest(request);

对我有用的是

var request = new NSUrl($"file://" + filepath);
Control.LoadFileUrl(request, request);

希望这对以后的人有帮助!