从plist中获取允许的文件类型的聪明方法

9

场景:

我想在我的Cocoa应用程序的Info.plist文件中定义允许的文件类型(内容类型)。因此,我按照以下示例将它们添加。

# Extract from Info.plist
[...]
<key>CFBundleDocumentTypes</key>
<array>
    <dict>
        <key>CFBundleTypeName</key>
        <string>public.png</string>
        <key>CFBundleTypeIconFile</key>
        <string>png.icns</string>
        <key>CFBundleTypeRole</key>
        <string>Viewer</string>
        <key>LSIsAppleDefaultForType</key>
        <true/>
        <key>LSItemContentTypes</key>
        <array>
            <string>public.png</string>
        </array>
    </dict>
[...]

此外,我的应用程序允许使用 NSOpenPanel 打开文件。该面板可以通过以下选择器设置允许的文件类型: setAllowedFileTypes:文档指出UTI可用

文件类型可以是常见的文件扩展名,也可以是UTI。


一种自定义解决方案:

我编写了以下帮助方法,从 Info.plist 文件中提取 UTI。

/**
    Returns a collection of uniform type identifiers as defined in the plist file.
    @returns A collection of UTI strings.
 */
+ (NSArray*)uniformTypeIdentifiers {
    static NSArray* contentTypes = nil;
    if (!contentTypes) {
        NSArray* documentTypes = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDocumentTypes"];
        NSMutableArray* contentTypesCollection = [NSMutableArray arrayWithCapacity:[documentTypes count]];
        for (NSDictionary* documentType in documentTypes) {
            [contentTypesCollection addObjectsFromArray:[documentType objectForKey:@"LSItemContentTypes"]];
        }
        contentTypes = [NSArray arrayWithArray:contentTypesCollection];
        contentTypesCollection = nil;
    }
    return contentTypes;
}

除了使用[NSBundle mainBundle],也可以使用CFBundleGetInfoDictionary(CFBundleGetMainBundle())


问题:

  1. 你是否知道从Info.plist文件中提取内容类型信息的更智能的方法?是否有Cocoa内置函数?
  2. 如何处理可能包含在其中的文件夹的定义,例如public.folder

注:
在我的研究过程中,我发现这篇文章非常有用:使用统一类型标识符简化数据处理

1个回答

1

以下是我如何从plist文件中读取信息的方法(它可以是info.plist或您项目中的任何其他plist,只要您设置了正确的路径)

NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSString *fullPath = [NSString stringWithFormat:@"%@/path/to/your/plist/my.plist", resourcePath];
NSData *plistData = [NSData dataWithContentsOfFile:fullPath];
NSDictionary *plistDictionary = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:0 errorDescription:nil];
NSArray *fileTypes = [plistDictionary objectForKey:@"CFBundleDocumentTypes"];

我喜欢你使用的 NSPropertyListSerialization。不过,你的解决方案需要知道 plist 文件的路径。- 那我的问题的第二部分呢? - JJD
我不确定我理解你问题的第二部分,如果你能再澄清一些,我很乐意尝试为你找到一个解决方案。 - Scott Sherwood
据我所了解,您可以为单个文件类型、一组文件类型(如public.image)和文件夹(public.folder)指定UTI。如何通过“文件/打开”和“拖放到应用程序图标上”允许在您的应用程序中打开图像(单个/多个/文件夹)?请避免冗余的UTI定义。 - JJD

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接