使用 Swift 查询可用的 iOS 磁盘空间

2024-06-28

我正在尝试使用以下命令获取可用的 iOS 设备存储空间Swift。我发现了这个功能here https://stackoverflow.com/a/25142432/633251

        func deviceRemainingFreeSpaceInBytes() -> NSNumber {
          let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
          let systemAttributes = NSFileManager.defaultManager().attributesOfFileSystemForPath(documentDirectoryPath.last as String, error: nil)
          return systemAttributes[NSFileSystemFreeSize] as NSNumber
        }

但是在编译的时候出现了这个错误:[NSObject : AnyObject]? does not have a member named 'subscript'我相信这个错误是由提到的问题引起的here https://stackoverflow.com/a/25451390/633251,即attributesOfFileSystemForPath返回一个可选的字典(文档 https://developer.apple.com/Library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/index.html#//apple_ref/occ/instm/NSFileManager/attributesOfFileSystemForPath:error:)。我从一般意义上理解这个问题,但是因为建议的解决方案涉及嵌套案例,所以我不太明白如何修复我感兴趣的函数(这并没有帮助,因为我对Swift)。有人可以建议如何使该功能发挥作用吗?注意:我不确定原始函数是否经过作者测试,或者它是否在 xcode 6 beta 下工作,但据我所知,它在 GM 下不起作用。


iOS 11 更新

下面给出的答案在 iOS 11 下不再提供准确的结果。有新的音量容量键可以传递给URL.resourceValues(forKeys:)提供与设备设置中可用的值相匹配的值。

  • static let volumeAvailableCapacityKey: URLResourceKey卷的可用容量(以字节为单位)的键(只读)。

  • static let volumeAvailableCapacityForImportantUsageKey: URLResourceKey用于存储重要资源的卷的可用容量(以字节为单位)的键(只读)。

  • static let volumeAvailableCapacityForOpportunisticUsageKey: URLResourceKey用于存储非必需资源的卷的可用容量(以字节为单位)的键(只读)。

  • static let volumeTotalCapacityKey: URLResourceKey卷总容量的键(以字节为单位)(只读)。

From 苹果的文档 https://developer.apple.com/documentation/foundation/urlresourcekey/checking_volume_storage_capacity:

Overview

在尝试在本地存储大量数据之前,请首先验证您是否有足够的存储容量。要获取卷的存储容量,您可以构造一个引用要查询的卷上的对象的 URL(使用 URL 的实例),然后查询该卷。

决定使用哪种查询类型

使用的查询类型取决于存储的内容。如果您根据用户请求或应用程序正常运行所需的资源来存储数据(例如,用户将要观看的视频或游戏中下一个级别所需的资源),请查询volumeAvailableCapacityForImportantUsageKey。但是,如果您以更具预测性的方式下载数据(例如,下载用户最近观看过的电视剧的新剧集),请查询volumeAvailableCapacityForOpportunisticUsageKey.

构造一个查询

使用此示例作为构建您自己的查询的指南:

let fileURL = URL(fileURLWithPath: NSHomeDirectory() as String)
do {
    let values = try fileURL.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
    if let capacity = values.volumeAvailableCapacityForImportantUsage {
        print("Available capacity for important usage: \(capacity)")
    } else {
        print("Capacity is unavailable")
    }
} catch {
    print("Error retrieving capacity: \(error.localizedDescription)")
}

原答案

可选装订 with if let也在这里工作。

我建议该函数返回一个可选的Int64,这样它就可以返回nil发出失败信号:

func deviceRemainingFreeSpaceInBytes() -> Int64? {
    let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    if let systemAttributes = NSFileManager.defaultManager().attributesOfFileSystemForPath(documentDirectoryPath.last as String, error: nil) {
        if let freeSize = systemAttributes[NSFileSystemFreeSize] as? NSNumber {
            return freeSize.longLongValue
        }
    }
    // something failed
    return nil
}

斯威夫特 2.1 更新:

func deviceRemainingFreeSpaceInBytes() -> Int64? {
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
    guard
        let systemAttributes = try? NSFileManager.defaultManager().attributesOfFileSystemForPath(documentDirectory),
        let freeSize = systemAttributes[NSFileSystemFreeSize] as? NSNumber
    else {
        // something failed
        return nil
    }
    return freeSize.longLongValue
}

斯威夫特 3.0 更新:

func deviceRemainingFreeSpaceInBytes() -> Int64? {
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
    guard
        let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: documentDirectory),
        let freeSize = systemAttributes[.systemFreeSize] as? NSNumber
    else {
        // something failed
        return nil
    }
    return freeSize.int64Value
}

Usage:

if let bytes = deviceRemainingFreeSpaceInBytes() {
    print("free space: \(bytes)")
} else {
    print("failed")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Swift 查询可用的 iOS 磁盘空间 的相关文章

随机推荐