How to get storage capacity of mac programmatically?

1.7k views Asked by At

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.

enter image description here

2

There are 2 answers

0
Manthan On BEST ANSWER

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...

2
Ken Thomases On

Use -[NSFileManager mountedVolumeURLsIncludingResourceValuesForKeys:options:] to get NSURLs 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.