The following is what I use to get the available storage space on an iOS device for my app:
NSDictionary *dict = [[NSFileManager defaultManager] fileSystemAttributesAtPath:@"/var"];
NSNumber *freeSpace = [dict valueForKey:@"NSFileSystemFreeSize"];
However, the value freeSpace
does not correspond with the one shown in the Settings app. The value is always greater than the value shown by Settings. For example, freeSpace
is approximately 600,000,000 bytes, where Settings shows 357 MB.
Why is this and how can I get the same value as the value shown by Settings?
Under iOS 11, there are new volume capacity keys that can be passed to URL.resourceValues(forKeys:)
that provide values that match what is available in device settings.
static let volumeAvailableCapacityKey: URLResourceKey
Key for the volume’s available capacity in bytes (read-only).
static let volumeAvailableCapacityForImportantUsageKey: URLResourceKey
Key for the volume’s available capacity in bytes for storing important resources (read-only).
static let volumeAvailableCapacityForOpportunisticUsageKey: URLResourceKey
Key for the volume’s available capacity in bytes for storing nonessential resources (read-only).
static let volumeTotalCapacityKey: URLResourceKey
Key for the volume’s total capacity in bytes (read-only).
From Apple's documentation:
Overview
Before you try to store a large amount of data locally, first verify that you have sufficient storage capacity. To get the storage capacity of a volume, you construct a URL (using an instance of URL) that references an object on the volume to be queried, and then query that volume.
Decide Which Query Type to Use
The query type to use depends on what's being stored. If you’re storing data based on a user request or resources the app requires to function properly (for example, a video the user is about to watch or resources that are needed for the next level in a game), query against
volumeAvailableCapacityForImportantUsageKey
. However, if you’re downloading data in a more predictive manner (for example, downloading a newly available episode of a TV series that the user has been watching recently), query againstvolumeAvailableCapacityForOpportunisticUsageKey
.Construct a Query
Use this example as a guide to construct your own query:
let fileURL = URL(fileURLWithPath:"/")
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)")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With