近日在開發歲寒輸入法的主題功能,為了實現導出主題包功能,頗費一番周折,最終代碼也不復雜,我在本文中簡單作個介紹。
我這里仍然是要使用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為文件的完整路徑
最終效果
注意:在虛擬機下是打不開導出菜單的,要在真機才行。