使用Swift获取已装入的卷列表?

时间:2015-07-30 10:20:13

标签: macos swift cocoa mounted-volumes

有谁知道如何获取使用Swift挂载的所有可移动卷的列表?

我已经尝试过这个,但它会返回外部驱动程序的所有文件和子文件夹的列表:

let filemanager:NSFileManager = NSFileManager()
        let files = filemanager.enumeratorAtPath("/Volumes")


        while let file = files?.nextObject() {
            println(file)
            menu.addItem(NSMenuItem(title: file as! String, action: Selector(""), keyEquivalent: ""))
        }

1 个答案:

答案 0 :(得分:12)

这将打印所有已装载卷的列表:

let filemanager = NSFileManager()
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = filemanager.mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: nil)
if let urls = paths as? [NSURL] {
    for url in urls {
        println(url)
    }
}

您当然可以过滤以获取"卷"中的路径。目录:

let filemanager = NSFileManager()
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = filemanager.mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: nil)
if let urls = paths as? [NSURL] {
    for url in urls {
        if url.relativePath?.pathComponents.count > 1 {
            if url.relativePath?.pathComponents[1] == "Volumes" {
                println(url)
            }
        }
    }
}

对于Swift 2,存在两个不同之处:对于文件管理器的选项,传递[]而不是nil,并且无需投射数组NSURLs:

let filemanager = NSFileManager()
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = filemanager.mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: [])
if let urls = paths {
    for url in urls {
        if url.relativePath?.pathComponents.count > 1 {
            if url.relativePath?.pathComponents[1] == "Volumes" {
                print(url)
            }
        }
    }
}

Swift 2.1的更新

let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = NSFileManager().mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: [])
if let urls = paths {
    for url in urls {
        if let components = url.pathComponents
            where components.count > 1
            && components[1] == "Volumes" {
                print(url)
        }
    }
}

Swift 3的更新

let keys: [URLResourceKey] = [.volumeNameKey, .volumeIsRemovableKey, .volumeIsEjectableKey]
let paths = FileManager().mountedVolumeURLs(includingResourceValuesForKeys: keys, options: [])
if let urls = paths {
    for url in urls {
        let components = url.pathComponents
        if components.count > 1
           && components[1] == "Volumes"
        {
            print(url)
        }
    }
}