2016-11-30 34 views
0

NSMetadataQuery類似乎是Finder/Spotlight通過元數據搜索文件的方式。如何通過Spotlight文件元數據屬性/ NSMetadataQuery過濾文件URL的NSArray?

NSMetadataQuery class provided by the Foundation framework. Queries can be run in two modes: asynchronous, and asynchronous with live updates. The first simply performs the search on the files that exist at the time of the initial search. The latter continues to search. updating the data as the files that fulfill or no longer fulfill the search parameters update.

https://developer.apple.com/library/content/documentation/Carbon/Conceptual/SpotlightQuery/Concepts/Introduction.html#//apple_ref/doc/uid/TP40001843-BBCFBCAG

然而,似乎周圍的導向提供了一個目錄(searchScopes),並在這些目錄(NSMetadataQueryDidFinishGathering)被發現,然後異步返回結果。

我已經有一個NSArray包含文件的URL。我想使用與Spotlight搜索相同的元數據和查詢語法來構造過濾/搜索這些NSURL。但是我會提供一個文件列表來快速filer,而不是提供一個目錄和接收異步結果。

// Something like this... 
let imageFileTypePredicate = NSPredicate(fromMetadataQueryString: "(kMDItemGroupId = 13)") 
let imageURLs = allURLs.filter{ imageFileTypePredicate.evaluate(with:$0) }; 

但是,使用標準NSPredicate搜索,而不是文件元數據過濾器,並引發錯誤:

this class is not key value coding-compliant for the key _kMDItemGroupId.

聚光燈元數據屬性我感興趣的是通過這裏列出過濾:
https://developer.apple.com/library/content/documentation/CoreServices/Reference/MetadataAttributesRef/Reference/CommonAttrs.html#//apple_ref/doc/uid/TP40001694-SW1

如何通過Spotlight元數據過濾文件URL的數組?

回答

0

爲每個url創建一個MDItem來獲取文件的聚光燈屬性。

MDItem is a CF-compliant object that represents a file and the metadata associated with the file.

https://developer.apple.com/reference/coreservices/1658213-mditem

MDItemRef item = MDItemCreateWithURL(kCFAllocatorDefault, url); 
CFArrayRef attributes = MDItemCopyAttributeNames(item); 
NSDictionary *attributeValues = CFBridgingRelease(MDItemCopyAttributes(item, attributes));