Xamarin формы: Word do c не открывается в ios приложении - PullRequest
0 голосов
/ 01 апреля 2020

Я использую Device.OpenUri(new Uri(word_doc_url)); для открытия слова / pdf do c в моем приложении. Документы PDF открываются нормально, но документы Word не открываются на устройствах ios. Отображение AccessdeniedAccess сообщения при открытом слове do c on iPhone.

Снимок экрана

[! [Введите описание изображения здесь] [1]] [1 ]

Я добавил ключ NSAppTransportSecurity в свой info.plist.

Снимок экрана

[! [Введите описание изображения здесь] [2 ]] [2]

Также опробовал функцию веб-просмотра для открытия слова do c в приложении согласно [этой теме] [3].

PdfWebView.cs в PCL

public class PdfWebView : WebView
{
    public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
    returnType: typeof(string),
    declaringType: typeof(PdfWebView),
    defaultValue: default(string));
    public string Uri
    {
        get { return (string)GetValue(UriProperty); }
        set { SetValue(UriProperty, value); }
    }
}

PdfWebViewRenderer.cs

[assembly: ExportRenderer(typeof(PdfWebView), typeof(PdfWebViewRenderer))]
namespace Projectname.iOS.Renderer
{
    class PdfWebViewRenderer : ViewRenderer<PdfWebView, UIWebView>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<PdfWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                SetNativeControl(new UIWebView());
            }
            if (e.OldElement != null)
            {
                // Cleanup
            }
            if (e.NewElement != null)
            {
                var customWebView = Element as PdfWebView;
                string fileName = Path.Combine(NSBundle.MainBundle.BundlePath, string.Format("Content/{0}", WebUtility.UrlEncode(customWebView.Uri)));
                Control.LoadRequest(new NSUrlRequest(new NSUrl(fileName, false)));
                Control.ScalesPageToFit = true;
            }
        }
    }
}

В XAML и XAML.cs:

<local:PdfWebView 
    HorizontalOptions="FillAndExpand"
    VerticalOptions="FillAndExpand"
    x:Name="pdf_Webview"/>

pdf_Webview.Source = pdfurl;
pdf_Webview.Uri = pdfurl;   

Но PDF и слово файлы не отображаются в webview.

1 Ответ

1 голос
/ 01 апреля 2020

Вы можете использовать библиотеку QuickLook для предварительного просмотра файла, встроенного или локального

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

using Foundation;
using UIKit;
using Xamarin.Forms.Platform.iOS;
using QuickLook;
//...[assembly]
namespace xxx.iOS
{

    public class PreviewItem : QLPreviewItem
    {

        NSUrl fileUrl;

        public override string ItemTitle
        {
            get { return fileUrl.LastPathComponent; }
        }

        public override NSUrl ItemUrl
        {
            get { return fileUrl; }
        }

        public PreviewItem(string filePath)
        {
            fileUrl = NSUrl.FromString(filePath);


        }
    }

    class MyWebViewRenderer:ViewRenderer<PdfWebView, UIWebView>,IQLPreviewControllerDataSource,IQLPreviewControllerDelegate
    {
        string filePath;

        public IQLPreviewItem GetPreviewItem(QLPreviewController controller, nint index)
        {
            return new PreviewItem(filePath);
        }

        public nint PreviewItemCount(QLPreviewController controller)
        {
            return 1;
        }

        [Export("previewController:shouldOpenURL:forPreviewItem:")]
        public bool ShouldOpenUrl(QLPreviewController controller,NSUrl url, QLPreviewItem item)
        {
            return true;
        }

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

            if (Control == null)
            {
                SetNativeControl(new UIWebView());
            }
            if (e.OldElement != null)
            {
                // Cleanup
            }
            if (e.NewElement != null)
            {
                var customWebView = Element as PdfWebView;
                filePath = Path.Combine(NSBundle.MainBundle.BundlePath, string.Format("Content/{0}", WebUtility.UrlEncode(customWebView.Uri)));

                var previewController = new QLPreviewController();


                previewController.WeakDelegate = this;
                previewController.DataSource = this;

                previewController.CurrentPreviewItemIndex = 0;

                var currentViewController = topViewControllerWithRootViewController(UIApplication.SharedApplication.Delegate.GetWindow().RootViewController);
                currentViewController.PresentViewController(previewController, true, null);
            }
        }




        UIViewController topViewControllerWithRootViewController(UIViewController rootViewController)
        {
            if (rootViewController is UITabBarController)
            {
                UITabBarController tabBarController = (UITabBarController)rootViewController;
                return topViewControllerWithRootViewController(tabBarController.SelectedViewController);
            }
            else if (rootViewController is UINavigationController)
            {
                UINavigationController navigationController = (UINavigationController)rootViewController;
                return topViewControllerWithRootViewController(navigationController.VisibleViewController);
            }
            else if (rootViewController.PresentedViewController != null)
            {
                UIViewController presentedViewController = rootViewController.PresentedViewController;
                return topViewControllerWithRootViewController(presentedViewController);
            }
            else
            {
                return rootViewController;
            }
        }

    }
}

. Вам лучше открыть QLPreviewController непосредственно на ContentPage в iOS вместо добавить веб-просмотр (использовать средство визуализации страниц).

Вариант 2

Вы можете добавить префикс Microsoft Office Preview

Device.OpenUri(new Uri("https://view.officeapps.live.com/op/view.aspx?src=your 
 file url"));

Он отлично работает на моей стороне. Похоже, ваш URL-адрес загрузит файл напрямую, поэтому убедитесь, что URL-адрес доступен.

...