Volume opportunistic available capacity differs so much and too low

94 Views Asked by At

I'm trying to figure out how much free space is left on my iPhone device but even though it has enough storage(more than 40gb), it returns Volume opportunistic available capacity to zero(0) or sometimes less than 20mb. I don't know how it calculates the opportunistic available capacity, but I wish to use it because I assume that it's safe to use this than Volume important available capacity. Is it possible to return such low number even when the iPhone storage is efficient?

        let freeSpace: CGFloat = {
            let fileURL = URL(fileURLWithPath: NSHomeDirectory() as String)
            do {
                let values = try fileURL.resourceValues(forKeys: [.volumeAvailableCapacityForOpportunisticUsageKey])
                if let capacity = values.volumeAvailableCapacityForOpportunisticUsage {
                    return CGFloat(capacity)
                } else {
                    return 0
                }
            } catch {
                return 0
            }
        }()

I want to know why opportunistic available capacity differs so much from the important available capacity.

1

There are 1 best solutions below

1
On

The difference in reported values between the opportunistic available capacity and the important available capacity could be due to various factors related to how iOS manages storage on the device.

The opportunistic available capacity represents the amount of storage that is currently available for opportunistic tasks, such as caching and temporary data. It takes into account the space that can be used temporarily, with the understanding that it may be reclaimed by the system if needed. This value can fluctuate based on system conditions and resource demands.

On the other hand, the important available capacity represents the amount of storage that is available for critical data, such as user-generated content or essential app functionality. This value is typically more conservative and takes into consideration the long-term storage needs and system stability.

To get the real amount of storage left on your device you need to reach into the filemanagers documentdirectory path:

enum StorageCapacityError: Error {
    case unavailable
}


func getAvailableStorageCapacity() throws -> Result<UInt64, Error> {
    let fileManager = FileManager.default
    let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    
    do {
        let attributes = try fileManager.attributesOfFileSystem(forPath: documentDirectoryURL.path)
        if let freeSize = attributes[.systemFreeSize] as? NSNumber {
            return .success(freeSize.uint64Value)
        } else {
            return .failure(StorageCapacityError.unavailable)
        }
    } catch {
        return .failure(error)
    }
}