文件元数据和文件查询,类似于 Spotlight。
请查看包含的示例应用程序。
完整的文档请参考 在线文档。
MetadataItem
允许你访问文件的元数据。
let videoFile = URL(filePathWithString: pathToFile)
if let metadata = videoFile.metadata {
metadata.duration // video duration
metadata.lastUsedDate // last usage date
metadata.pixelSize // video pixel size
}
一种文件查询,提供:
每当新文件在搜索位置满足指定的谓词时,结果处理程序就会被调用。
该谓词通过将 MetadataItem
属性与使用运算符和函数的值进行比较来构建。
let query = MetadataQuery()
// Searches for files at the downloads and documents directory
query.searchLocations = [.downloadsDirectory, .documentsDirectory]
// Image & videos files, added this week, large than 10mb
query.predicate = {
$0.fileTypes(.image, .video) &&
$0.addedDate.isThisWeek &&
$0.fileSize.megabytes >= 10
}
query.resultsHandler = { files, _ in
// found files
}
query.start()
MetadataQuery 为大批量文件提供极速属性查询。 获取数千个文件的属性通常只需不到一秒的时间。
// URLs for querying of attributes
query.urls = videoFileURLs
// Attributes to query
query.attributes = [.pixelSize, .duration, .fileSize, .creationDate]
query.resultsHandler = { files, _ in
for file in files {
// file.pixelSize, file.duration, file.fileSize, file.creationDate
}
}
query.start()
MetadataQuery 可以监控搜索结果和查询属性的更改。 每当发生更改时,它都会调用 completionHandler。
要启用监控,请使用 monitorResults()
。
// Files that are screenshots
query.predicate = { $0.isScreenCapture }
// Searches everywhere on the local file system
query.searchScopes = [.local]
// Enables monitoring. Whenever a new screenshot gets captures the results handler gets called
query.monitorResults = true
query.resultsHandler = { files, _ in
for file in files {
// screenshot files
}
}
query.start()