获取Macintosh HD磁盘下的目录列表:
let fileManager = FileManager.default
let resourceKeys: [URLResourceKey] = [.volumeNameKey, .volumeLocalizedFormatDescriptionKey,.localizedNameKey,.fileSizeKey,.isDirectoryKey,.isPackageKey,.effectiveIconKey]
let fileEnum = fileManager.enumerator(at: URL(string: "/")!, includingPropertiesForKeys: resourceKeys,options: .skipsHiddenFiles,errorHandler: nil)
let fileURL = fileEnum?.first
if let volumes = fileManager.mountedVolumeURLs(includingResourceValuesForKeys: resourceKeys, options: .skipHiddenVolumes) {
for volume in volumes {
if let resources = try? volume.resourceValues(forKeys: Set(resourceKeys)),
let name = resources.volumeName,
let format = resources.volumeLocalizedFormatDescription {
print("Disk Info:\(name), format: \(format)")
if name == "Macintosh HD" {
filesList = contentsOf(folder: URL(string: "/")!)
print("File List:\(filesList)")
tableView.reloadData()
}
}
}
}
获取文件列表的函数:
//get files list
func contentsOf(folder: URL) -> [URL] {
let fileManager = FileManager.default
do {
let contents = try fileManager.contentsOfDirectory(atPath: folder.path)
let urls = contents
.filter { return showInvisibles ? true : $0.first != "." }
.map { return folder.appendingPathComponent($0) }
return urls
} catch {
return []
}
}
获取文件信息的函数:
// file info
func infoAbout(url: URL) -> String {
let fileManager = FileManager.default
do {
let attributes = try fileManager.attributesOfItem(atPath: url.path)
var report: [String] = ["\(url.path)", ""]
for (key, value) in attributes {
// ignore NSFileExtendedAttributes as it is a messy dictionary
if key.rawValue == "NSFileExtendedAttributes" { continue }
report.append("\(key.rawValue):\t \(value)")
}
return report.joined(separator: "\n")
} catch {
return "No information available for \(url.path)"
}
}
获取文件图标的代码:
let item = filesList[row]
let fileIcon = NSWorkspace.shared.icon(forFile: item.path)