背景介绍
一般来说导入导出的可以是任何数据,但无论何种数据,都要给数据的类型起一个名称,以便系统能够筛选出支持的软件(否则,列出所有的安装软件用户选择麻烦,如果用户选择一个不支持的软件也可能导致触发未知的行为)。
这个数据类型有固定的标准UTI,全称为Uniform Type Identifiers,这个链接有比较详细的介绍
所以,支持导出的软件,就要事先声明支持导出的数据类型。支持导入的软件,要声明支持导入的数据类型。
下面都是以扩展名.md的文件为数据类型,进行说明。
配置文件
配置文件为Info.plist,这个文件应该已经在项目里啦。主要添加三段:
1、声明类型,添加如下代码:
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string></string>
</array>
<key>CFBundleTypeIconFiles</key>
<array/>
<key>CFBundleTypeName</key>
<string>MarkDownType</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>com.test.markdown</string>
</array>
</dict>
</array>
2、导出声明,添加如下代码:
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.text</string>
<string>public.plain-text</string>
</array>
<key>UTTypeDescription</key>
<string>mark down document</string>
<key>UTTypeIconFiles</key>
<array/>
<key>UTTypeIdentifier</key>
<string>com.test.markdown</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>md</string>
</array>
<key>public.mime-type</key>
<string>text/x-markdown</string>
</dict>
</dict>
</array>
3、导入声明,添加代码和第2段类似,只是把<key>UTExportedTypeDeclarations</key>替换成<key>UTImportedTypeDeclarations</key>
备注:使用时,把com.test.markdown换成真实的。另,这个是md文件扩展名的。
如果对plist文件格式不了解的,可能不知道怎么添加。实际上,这个文件都是键值对的数据结构。添加的这3段都作为根Dict节点的子就可以,和其他子的前后顺序不重要。
导出文件
导出主要使用UIActivityViewController类,简单实现代码如下:
// url是要分享文件的url,为URL实例
let controller = UIActivityViewController(activityItems: [url], applicationActivities:nil)
controller.excludedActivityTypes = [.postToVimeo, .addToReadingList]
if UIDevice.current.userInterfaceIdiom == .pad {
// 需要设置controller.popoverPresentationController?.sourceView和
// controller.popoverPresentationController?.sourceRect
// 表示的是气泡起始位置(箭头、可能根据屏幕显示的区域进行调整)
// 不是气泡的显示区域
}
// viewController为当前显示的UIViewController的实例
viewController?.present(controller, animated:false) {
}
导入文件
导入协议在不同系统版本略有不同,这里只描述ios 13.0及以后版本。
项目默认有两个代理类实例:分别为AppDelegate和SceneDelegate。
1、在程序没有启动时,导入会启动该程序,此时AppDelegate.application(_application:UIApplication, configurationForConnecting connectingSceneSession:UISceneSession, options:UIScene.ConnectionOptions) ->UISceneConfiguration方法会被调用,启动的url在参数options中(可能存在多个url)。
2、在程序启动后,导入调用SceneDelegate.scene(_scene:UIScene, openURLContexts URLContexts:Set)方法,url在参数URLContexts中(也可能存在多个url)。