近日在开发岁寒输入法的主题功能,为了实现导出主题包功能,颇费一番周折,最终代码也不复杂,我在本文中简单作个介绍。
我这里仍然是要使用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为文件的完整路径
最终效果
注意:在虚拟机下是打不开导出菜单的,要在真机才行。