文章目录
简述
右键点击图片,打开方式中可以选择不同的app,如果希望我们的app,在右键选择时,能够出现关联,则需要添加 Document Type。
添加方法
方法一
1、在 Targets --> Info --> Document Types 里面添加需要的类型。
比如我需要关联 gif、png、webP
其中 identifier 是一个常量,不能随便设置,可参考官方文档:
https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
2、在 delegate中添加代码
-(void)application:(NSApplication *)application openURLs:(NSArray<NSURL *> *)urls{
NSLog(@"urls : %@",urls);
}
验证 & 运行效果
添加完成后,运行程序。运行时,系统会将该app的document type 注册上去。
找到文件夹中的png,或者gif 图片,右击–>打开方式,就可以看到我们的app了。
选中我们的app后,程序打印台会打印类似如下日志:
2018-03-07 15:07:22.910279+0800 MacCodeGen[58066:2351042] urls : (
"file:///Users/MelissaShu/Pictures/pathForResource.png"
)
方法二
添加后,内容也会体现在 info.plist 中
使用sourceCode 查看,可以发现增加了如下代码:
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>gif</string>
</array>
<key>CFBundleTypeName</key>
<string>GIF image</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSHandlerRank</key>
<string>Default</string>
<key>LSItemContentTypes</key>
<array>
<string>com.compuserve.gif</string>
</array>
</dict>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>png</string>
</array>
<key>CFBundleTypeName</key>
<string>PNG image</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSHandlerRank</key>
<string>Default</string>
<key>LSItemContentTypes</key>
<array>
<string>public.png</string>
</array>
</dict>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>webp</string>
</array>
<key>CFBundleTypeName</key>
<string>WebP image</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSHandlerRank</key>
<string>Default</string>
<key>LSItemContentTypes</key>
<array>
<string>com.google.webp</string>
<string>public.webp</string>
</array>
</dict>
</array>
也可以直接将上述代码添加到 info.plist 的code 中来设置支持格式。
CFBundleDocumentTypes 中的字段
CFBundleDocumentTypes 数组中的每个 dictionary 可能包含以下键:
CFBundleTypeName
指定文档类型名称。
CFBundleTypeExtensions
文件类型,比如:pdf,doc,xls等,不可乱填,
CFBundleTypeIconFiles
是一个数组,包含多个图片文件名,用于作为该文档的图标,显示在活动列项中。一般用的是app的icon。
Document Content Type UTIs
指定官方指定的文件类型,
参考资料
- 官方文档:Registering the File Types Your App Supports
https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Articles/RegisteringtheFileTypesYourAppSupports.html - Mossion:iOS 让自己的应用 在其他应用中打开
https://www.jianshu.com/p/9711c3daf4bb