遍历已装入的卷以查找特定文件类型

时间:2017-11-29 14:28:01

标签: swift macos nsfilemanager

我试图找出如何扫描已安装的卷(它们连接到服务器并通过afp://挂载到我的工作站上)并选择某些文件类型,并输出路径,文件名和资产id到csv文件。资产ID是文件名后面加“_”的最后10位数(例如: afilename_1234567890.mov )有些文件没有资产ID(我忽略),有些文件有多个“。”(例如, afilename_videofile_23.98_prores_1234567890.mov )。我可以获得我需要的卷(更少的时间机器备份驱动器),但尝试扫描文件是很麻烦的。我查看了各种示例并研究了Apple FileManager文档,但没有具体的内容。

我有以下例程来执行我需要的操作但是使用 let enumerator = fileManager.enumerator(atPath:url.path)!,枚举器始终为空。

要么我做出错误的假设,要么我肯定错过了至关重要的事情。

func FindFilesWithAssetIDs() {

    // Find all the mounted volumes
    let keys: [URLResourceKey] = []
    let volumes = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: keys, options: [])!

    var count = 0
    var volumeCount = volumes.count
    var volumeItem = 0

    let filterExtensions = ["mxf", "mov", "mp4", "scc", "cap", "srt", "txt", "rtf", "wav", "mp3", "m2v", "aif"]

    // Scan all the mounted volumes, one at a time
    for url in volumes {

        let components = url.pathComponents

        if components.count > 1  && components[1] == "Volumes" {
            if components[2] == "Time Machine Backup" { continue } // Check if the volume is the staff backup disk. If it is, move on to the next volume

            guard let volumeTypeKey = try? url.resourceValues(forKeys: [.volumeIsLocalKey]) else { return } // Make sure we are scanning the volumes and not any local folders like /private

            let volumeType: Bool = volumeTypeKey.volumeIsLocal!

            if volumeType == false {
                let fileManager = FileManager.default
                let enumerator = fileManager.enumerator(atPath: url.path)!

                while let element = enumerator.nextObject() as? String {
                    if element.hasSuffix("mxf") || element.hasSuffix("mov") { // a test. I would much rather use a filterExtension method or a switch statement
                        // do something
                        count += 1
                    }
                }

                NSLog(url.path, " ", String(count))
                //                    NSLog(url.path)
            }
        }

        volumeItem += 1
    }
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

我没有使用nsfilemanager枚举,而是建议使用NSMetadataQuery又名Spotlight。请参阅此处了解简介:https://developer.apple.com/library/content/documentation/Carbon/Conceptual/SpotlightQuery/Concepts/QueryingMetadata.html#//apple_ref/doc/uid/TP40001848-CJBEJBHH

答案 1 :(得分:0)

我尝试使用Applescript来扫描卷,但有一些文件,即使它们存在,Spotlight也找不到它们。我在所有已安装的卷上重建了Spotlight数据库,但没有运气。由于这些错误,我使用了Swift。

在一天结束时,我在Swift和Applescript之后更进一步。我对代码做了一些更改(而let element = enumerator.nextObject()为?String 现在是而let element = enumerator.nextObject()为?URL 缩短String< - >的其他例程URL调用等。

我正在解决这个问题,因为它已经解决了。