7

有谁知道如何获取使用 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: ""))
}
4

2 回答 2

18

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

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)
    }
}

您当然可以过滤以仅获取“Volumes”目录中的路径:

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文件管理器的选项,并且不需要转换 NSURL 数组:

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)
        }
    }
}
于 2015-07-30T10:44:35.010 回答
0

在 Unix 系统上,系统文件编号为 2 的文件系统对象是挂载,无论是远程挂载(nfs、smb、afp)还是本地挂载。

这是一个例子:

let path = "/System/Volumes/Preboot"
let systemAttributes = try FileManager.default.attributesOfItem(atPath: String(describing: path))
if let fileSystemFileNumber = systemAttributes[.systemFileNumber] as? NSNumber {
    print("System File Number: \(fileSystemFileNumber)")
}

所以也许这可能是找到坐骑的捷径

于 2022-01-10T20:07:52.750 回答