Access metadata of a single file

1.9k Views Asked by At

Is there a way to programmatically access metadata of a single file on MacOS?

I know Apple provides NSMetadataQuery, but it seems it only allows to search in particular folders for files matching some parameters. Actually I'd prefer not to search for all files matching but check if a particular file matches.

Is there a way or the only solution is to analyze the results of the query and see if my file is among them?

2

There are 2 best solutions below

0
On BEST ANSWER

You can get the metadata the same way the command mdls gets its data. Search for MDItemCreate in the documentation. (you find : Core Library --> Data Management --> File Management --> MDItem Reference)
I hope the following method to create the metadata dictionary will give you what you need:

- (NSDictionary *) metaDataDictionaryForFileAt:(NSString *)fileName
{
    MDItemRef item = MDItemCreate( kCFAllocatorDefault, (CFStringRef)fileName );
    if( item==nil ) return nil;

    CFArrayRef list = MDItemCopyAttributeNames( item );
    NSDictionary *resDict = (NSDictionary *)MDItemCopyAttributes( item, list );
    CFRelease( list );
    CFRelease( item );
    return [resDict autorelease];
}

Remark: The value of kMDItemContentType, kMDItemContentTypeTree, and kMDItemKind are determined by the suffix of the filename not by the content of the file!

1
On

I don't think there's an API for this (which is odd, you should file a bug). If you don't want to run a query then your only other option would be to use NSTask to spawn an instance of the mdls command and then parse the results.