这将打印所有已安装卷的列表:
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)
}
}
}