I like to define the allowed file types (content types) in the Info.plist
file of my Cocoa application. Therefore, I added them like the following example shows.
# 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>
[...]
Further, my application allows to open files using an NSOpenPanel
. The panel allows to set the allowed file types through the following selector: setAllowedFileTypes:
. The documentation states that UTI can be used.
The file type can be a common file extension, or a UTI.
I wrote the following helper method to extract the UTI from the Info.plist
file.
/**
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;
}
Instead of [NSBundle mainBundle]
also CFBundleGetInfoDictionary(CFBundleGetMainBundle())
can be used.
Info.plist
file? Is there a Cocoa-build-in function? public.folder
?Note:
Throughout my research, I found this article quite informative: Simplifying Data Handling with Uniform Type Identifiers.
Here is how I read information from a plist (it can be the info.plist or any other plist you have in you project provided you set the correct path)
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With