Declare to determine the volume storage capacity for a device

According to my app’s error logs, a significant percentage of my users run out of storage while using my app. So I want to warn users if they are low on storage when they start the app.

This is Apple’s recommended way to do it: Checking Volume Storage Capacity

The code using NSURL looks similar to the declare code that @Greg_O_Lone shared last year to determine the temporary folder location. However I’ve had no success in repurposing Greg’s code. :frowning:

So, I was wondering … would any of the declare gurus be willing to have a go at writing a method to determine the volume storage capacity? :slight_smile:

I know this is really messy, but this code will work:

Declare Function alloc Lib "Foundation" selector "alloc" (cls as ptr) as ptr
Declare Function NSClassFromString Lib "Foundation" (name as cfstringref) as ptr
Declare Function fileURLWithPath_ Lib "Foundation" Selector "fileURLWithPath:" (cls as ptr, path as CFStringRef) As Ptr
Declare Function initWithCapacity_ Lib "Foundation" Selector "initWithCapacity:" (obj as ptr, numItems as Integer) As Ptr
Declare Sub addObject_ Lib "Foundation" Selector "addObject:" (obj as ptr, anObject as CFStringRef)
Declare Function resourceValuesForKeys_error_ Lib "Foundation" Selector "resourceValuesForKeys:error:" (obj as ptr, keys as Ptr, error as Ptr) As Ptr
Declare Function valueForKey_ Lib "Foundation" Selector "valueForKey:" (obj as ptr, key as CFStringRef) As Ptr
Declare Function getUnsignedIntegerValue Lib "Foundation" selector "unsignedIntegerValue" (obj as ptr) as UInteger

dim fileURL as ptr = fileURLWithPath_(NSClassFromString("NSURL"), "/")

dim keyArray as ptr = alloc(NSClassFromString("NSMutableArray"))
keyArray = initWithCapacity_(keyArray, 1)

const capacityKey as string = "NSURLVolumeTotalCapacityKey"
addObject_(keyArray,capacityKey )

dim error as ptr
dim results as ptr = resourceValuesForKeys_error_(fileURL, keyArray, error)
dim nsnum as ptr = valueForKey_(results, capacityKey) // this thing is an NSNumber

dim volumeSizeInBytes as UInteger = getUnsignedIntegerValue(nsnum)


Thanks so much Greg!

I had to change the capacityKey to “NSURLVolumeAvailableCapacityForImportantUsageKey” to get it to almost match the available space on my device as shown in the Finder, but that Apple page lists a number of keys to use for different purposes so others can play around with different keys to suit their needs.

I am very appreciative Greg. :slight_smile: