0

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Manthan
  • 3,856
  • 1
  • 27
  • 58
  • statfs(2) for C-based solution. https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/statfs.2.html – user3125367 Jun 10 '15 at 06:01

2 Answers2

4

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.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • Thanks for your reply. Can you please show me via code for getting a total capacity of mac as I am slightly new to mac development. Thanks... – Manthan Jun 10 '15 at 06:38
  • This is my partial solution to use NSURL and NSByteCountFormatter: `NSDictionary *resources = [url resourceValuesForKeys: keys error: &error]; NSLog(@"NSURL resources: %@", resources); if ([url getResourceValue: &availableSpace forKey: NSURLVolumeAvailableCapacityKey error: &error] == YES) { NSString *formattedAvailableSpace = [NSByteCountFormatter stringFromByteCount: [availableSpace longLongValue] countStyle: NSByteCountFormatterCountStyleFile]; NSLog(@"availableSpace: %@ formattedAvailableSpace: %@", availableSpace, formattedAvailableSpace); } ` – edenwaith May 13 '17 at 03:16
3

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

Community
  • 1
  • 1
Manthan
  • 3,856
  • 1
  • 27
  • 58