【发布时间】:2021-06-20 16:26:47
【问题描述】:
在 Swift (MacOS) 中如何确定 USB 驱动器的总空间、可用空间和已用空间?
有几篇关于此的好帖子(例如:How to get the Total Disk Space and Free Disk space using AttributesOfFileSystemForpaths in swift 2.0 和 https://developer.apple.com/documentation/foundation/urlresourcekey/checking_volume_storage_capacity),但它们都只是获取操作系统驱动器的空间,而不是 USB 驱动器的空间。
例如,我有一个卷名为“myusb”的 64GB USB 驱动器,因此 MacOS 将驱动器安装在 /Volumes/myusb。 Finder 显示 USB 驱动器的总空间为 62.91GB,可用为 62.29GB,使用为 625,999,872 字节。
问题似乎在于,当我给出 USB 驱动器的路径时,由于它显然是主 / 路径的一部分,它返回的 / 是我的操作系统驱动器的信息,而不是 USB 驱动器。
这是我在尝试确定 USB 驱动器的可用空间时所做的,它返回 292298430687 字节的值(这是我的操作系统驱动器的可用空间,而不是 USB 驱动器):
/**
Returns URL of root of USB drive - i.e. /Volumes/myusb
Uses bundleURL as .app file being executed is located on the USB drive
*/
static func getRootURL() -> URL {
let bundlePath = Bundle.main.bundleURL
let bundlePathComponents = bundlePath.pathComponents
let destinationRootPathURL = URL(fileURLWithPath: bundlePathComponents[0])
.appendingPathComponent(bundlePathComponents[1])
.appendingPathComponent(bundlePathComponents[2])
return destinationRootPathURL
}
/**
returns free space of USB drive
*/
func getAvailableSpaceInBytes() -> Int64 {
if #available(OSX 10.13, *) {
if let freeSpace = try? getRootURL().resourceValues(forKeys: [URLResourceKey.volumeAvailableCapacityForImportantUsageKey])
.volumeAvailableCapacityForImportantUsage {
return freeSpace
}
} else {
// Fallback on earlier versions
guard let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: getRootURL().path),
let freeSize = systemAttributes[FileAttributeKey.systemFreeSize] as? NSNumber
else {
// something failed so return nil
return 0
}
return freeSize.int64Value
}
return 0
}
【问题讨论】:
标签: swift macos usb storage file-manager