为什么“ volumeAvailableCapacityForImportantUsage”为零?

时间:2019-06-06 09:12:04

标签: ios swift

我正在关注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

为什么volumeAvailableCapacityForImportantUsagevolumeAvailableCapacityForOpportunisticUsage为零,在什么情况下会发生这种情况?

背景:

  • 我正在通过xCode 10.2.1在自己的64GB iPhone SE上运行此实验(因此总容量看起来正确)
  • 我的iPhone正在运行iOS11
  • iTunes声称我的设备有10.27GB的“免费”
  • 我正在尝试弄清楚这一点,以便我知道我的用户是否有足够的空间来下载大量(超过40MB)的应用内购买商品

注意:这与this question 不相同。我知道如何查询可用空间。我想了解该查询的结果。

1 个答案:

答案 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