在默认应用程序中打开文件

本文关键字:文件 默认 应用程序 | 更新日期: 2023-09-27 18:07:44

我以前用这种方式在默认应用程序中打开文档,但从iOS 10开始,它在iPhone上不起作用(应用程序崩溃),但在iPad上运行良好。

DependencyService打开文件的正确方法是什么?

由于我目前没有iOS 10设备可以测试,所以我无法找到这个错误。

在默认应用程序中打开文件

你需要知道你要打开的应用程序的URL Scheme;URL方案是应用程序之间唯一的通信方式。

你没有指定你要打开哪个应用程序,所以我在下面包含了示例代码,展示了如何使用URL方案打开设置应用程序,邮件应用程序和应用商店应用程序(到一个特定的应用程序)。

Apple有关于URL方案的附加文档在这里

using UIKit;
using MessageUI;
using Foundation;
using Xamarin.Forms;
using SampleApp.iOS;
[assembly: Dependency(typeof(DeepLinks_iOS))]
namespace SampleApp.iOS
{
    public class DeepLinks_iOS : IDeepLinks
    {
        public void OpenStoreLink()
        {
            Device.BeginInvokeOnMainThread(() => UIApplication.SharedApplication.OpenUrl(new NSUrl("https://appsto.re/us/uYHSab.i")));
        }
        public void OpenFeedbackEmail()
        {
            MFMailComposeViewController mailController;
            if (MFMailComposeViewController.CanSendMail)
            {
                mailController = new MFMailComposeViewController();
                mailController.SetToRecipients(new string[] { "support@gmail.com" });
                mailController.SetSubject("Email Subject String");
                mailController.SetMessageBody("This text goes in the email body", false);
                mailController.Finished += (object s, MFComposeResultEventArgs args) =>
                {
                    args.Controller.DismissViewController(true, null);
                };
                var currentViewController = GetVisibleViewController();
                currentViewController.PresentViewController(mailController, true, null);
            }
        }
        public void OpenSettings()
        {
            Device.BeginInvokeOnMainThread(() => UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString)));
        }

        static UIViewController GetVisibleViewController()
        {
            var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController;
            if (rootController.PresentedViewController == null)
                return rootController;
            if (rootController.PresentedViewController is UINavigationController)
            {
                return ((UINavigationController)rootController.PresentedViewController).TopViewController;
            }
             if (rootController.PresentedViewController is UITabBarController)
            {
                return ((UITabBarController)rootController.PresentedViewController).SelectedViewController;
            }
            return rootController.PresentedViewController;
        }
    }
}