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?
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!