在Xamarin.Form中实现iOS文件导出功能

近日在开发岁寒输入法的主题功能,为了实现导出主题包功能,颇费一番周折,最终代码也不复杂,我在本文中简单作个介绍。

我这里仍然是要使用DependencyService.

声明接口

namespace SuiHanLib {
    public interface IOutputTheme {
        void output(string path);
    }
}

在iOS项目中实现

using System;
using SuiHanLib;
using Foundation;
using UIKit;

[assembly: Xamarin.Forms.Dependency(typeof(SuiHanIME.iOS.OutputTheme_iOS))]
namespace SuiHanIME.iOS {
    public class OutputTheme_iOS : IOutputTheme {
        public OutputTheme_iOS() {
        }

        public void output(string path) {
            var nSUrl = NSUrl.FromFilename(path);
            var viewer = UIDocumentInteractionController.FromUrl(nSUrl);
            viewer.Uti = @"public.archive";//声明文件的类型
            var controller = GetVisibleViewController();
            viewer.PresentOpenInMenu(controller.View.Frame, controller.View, true);
        }

        // Search recursively for the top most UIViewController
        // Source: http://stackoverflow.com/questions/41241508/xamarin-forms-warning-attempt-to-present-on-whose-view-is-not-in-the-window
        private UIViewController GetVisibleViewController(UIViewController controller = null) {
            controller = controller ?? UIApplication.SharedApplication.KeyWindow.RootViewController;

            if (controller.PresentedViewController == null)
                return controller;

            if (controller.PresentedViewController is UINavigationController) {
                return ((UINavigationController)controller.PresentedViewController).VisibleViewController;
            }

            if (controller.PresentedViewController is UITabBarController) {
                return ((UITabBarController)controller.PresentedViewController).SelectedViewController;
            }

            return GetVisibleViewController(controller.PresentedViewController);
        }

    }
}

使用方法

    var openControl = DependencyService.Get<IOutputTheme>();
    openControl.output(path);//path为文件的完整路径

最终效果

注意:在虚拟机下是打不开导出菜单的,要在真机才行。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,284评论 25 708
  • 2017根据生命平衡轮,从这8个方面提出行为的方向。 职业发展:提升策划能力 之前一直想的是多做策划案例来提升,后...
    蒋羽燃阅读 238评论 1 1
  • 计算机以何种规则进行通信,就是网络研究问题。 网络模型一般是指: OSI(Open System Intercon...
    frankisbaby阅读 309评论 0 0
  • 余锦渊却没有如余笙担忧的那般起了疑心,那日太子回去后,宫内便传来圣旨,择日太子将迎娶太子妃,命他抓紧时间筹办余笙入...
    嘤语喃喃sherry阅读 237评论 0 1