我正在关注Apple's documented example,以了解如何查询设备上的可用磁盘空间。
我在applicationDidFinishLaunchingWithOptions
中使用以下代码:
let fileURL = URL(fileURLWithPath:"/")
do {
let values = try fileURL.resourceValues(forKeys: [
.volumeAvailableCapacityKey,
.volumeAvailableCapacityForImportantUsageKey,
.volumeAvailableCapacityForOpportunisticUsageKey,
.volumeTotalCapacityKey
])
print("Available Capacity: \(Float(values.volumeAvailableCapacity!)/1000000000)GB")
print("ImportantUsage Capacity: \(Float(values.volumeAvailableCapacityForImportantUsage!)/1000000000)GB")
print("Opportunistic Capacity: \(Float(values.volumeAvailableCapacityForOpportunisticUsage!)/1000000000)GB")
print("Total Capacity: \(Float(values.volumeTotalCapacity!)/1000000000)GB")
} catch {
print("Error retrieving capacity: \(error.localizedDescription)")
}
这将记录以下内容:
Available Capacity: 3.665879GB
ImportantUsage Capacity: 0.0GB
Opportunistic Capacity: 0.0GB
Total Capacity: 63.989494GB
为什么volumeAvailableCapacityForImportantUsage
和volumeAvailableCapacityForOpportunisticUsage
为零,在什么情况下会发生这种情况?
背景:
注意:这与this question 不相同。我知道如何查询可用空间。我想了解该查询的结果。
答案 0 :(得分:1)
问题是,您正在尝试获取/的系统卷的容量,该/是文件系统的根。该API的行为很奇怪,但是您可以获得所需的信息。如果您使用应用程序的文档目录,则FileManager
方法和.volumeAvailableCapacityKey
仍然会产生奇怪的值,但是现在您可以获得.volumeAvailableCapacityForImportantUsageKey
和.volumeAvailableCapacityForOpportunisticUsageKey
的有用值。
示例:
let f = ByteCountFormatter()
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
print("path = \(path)")
let attrs = try! FileManager.default.attributesOfFileSystem(forPath: path)
let fmFree = (attrs[.systemFreeSize] as! NSNumber).int64Value
print("FileManager.attributesOfFileSystem free: \(f.string(fromByteCount: fmFree))")
let docsURL = URL(fileURLWithPath: path)
let values = try! docsURL.resourceValues(forKeys: [.volumeAvailableCapacityKey, .volumeAvailableCapacityForImportantUsageKey, .volumeAvailableCapacityForOpportunisticUsageKey])
print("Volume available capacity: \(f.string(fromByteCount: Int64(values.volumeAvailableCapacity!)))")
print("Volume important available capacity: \(f.string(fromByteCount: values.volumeAvailableCapacityForImportantUsage!))")
print("Volume opportunistic available capacity: \(f.string(fromByteCount: Int64(values.volumeAvailableCapacityForOpportunisticUsage!)))")
在我的系统上打印:
FileManager.attributesOfFileSystem free: 8.51 GB
Volume available capacity: 8.51 GB
Volume important available capacity: 177.16 GB
Volume opportunistic available capacity: 175.88 GB