Reputation: 3914
How do I get the total capacity, available space and free space in Cocoa?
As shown in the screenshot, I want to get this programmatically in my Cocoa application for macOS.
Upvotes: 0
Views: 1882
Reputation: 3914
I got my answer from the link.
So I am posting what I did using that reference.
NSError *error;
NSFileManager *fm = [NSFileManager defaultManager];
NSDictionary *attr = [fm attributesOfFileSystemForPath:@"/"
error:&error];
NSLog(@"Attr: %@", attr);
float totalsizeGb = [[attr objectForKey:NSFileSystemSize]floatValue] / 1000000000;
NSLog(@" size in GB %.2f",totalsizeGb);
float freesizeGb = [[attr objectForKey:NSFileSystemFreeSize]floatValue] / 1000000000;
NSLog(@" size in GB %.2f",freesizeGb);
Hope that helps anyone else also.
Thanks...
Upvotes: 3
Reputation: 90721
Use -[NSFileManager mountedVolumeURLsIncludingResourceValuesForKeys:options:]
to get NSURL
s for the volumes. For the propertyKeys
, use @[ NSURLVolumeTotalCapacityKey, NSURLVolumeAvailableCapacityKey ]
. You probably want to use NSVolumeEnumerationSkipHiddenVolumes
in the options.
Then, for each URL, call -[NSURL resourceValuesForKeys:error:]
with the same property keys. This will give you a dictionary whose keys are NSURLVolumeTotalCapacityKey
and NSURLVolumeAvailableCapacityKey
and whose values are NSNumber
objects holding the corresponding quantities, measured in bytes.
If you need to format those values for display, use NSByteCountFormatter
.
Upvotes: 4