Get MacOS System Information in Objective C

If you need to find system information using Objective C , there is no single library or framework which provides all the information. Generally it is simpler to simply use existing command line tools and capture the output and parse the required information. For eg.to get information about disks, you can use the Disk Arbitration Framework or IOKit, but it is far simpler to capture the output of diskutil.

The system_profiler tool gives a very comprehensive output about almost all aspects of the system but its execution is slow , so it is better to use it only as a last resort.

Given below are code snippets to get various system information. Each is in the form of a function.

Get Disk Free Space


-(uint64_t)getFreeDiskspace {
    float totalSpace = 0;
    float totalFreeSpace = 0;
    float totalUsedSpace = 0;
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];

    if (dictionary) {
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        totalSpace = [fileSystemSizeInBytes floatValue];
        float terabyte =1024.0 * 1024.0 * 1024.0 * 1024.0;
        NSString *stotalSpace = [NSString stringWithFormat:@"%.3f GB",totalSpace/(1024*1024*1024)];
        if (totalSpace >= terabyte)
            stotalSpace = [NSString stringWithFormat:@"%.0f Tb",totalSpace/(1024*1024*1024*1024)];
        else  if (totalSpace >= (1024*1024*1024))
            stotalSpace = [NSString stringWithFormat:@"%.0f Gb",totalSpace/(1024*1024*1024)];
        else  if (totalSpace >= (1024*1024))
             stotalSpace = [NSString stringWithFormat:@"%.0f Mb",totalSpace/(1024*1024)];
        
                
        totalFreeSpace = [freeFileSystemSizeInBytes floatValue];
       
        totalUsedSpace = totalSpace - totalFreeSpace;
        float percent= (totalUsedSpace / totalSpace) * 100.0;
        NSString *spercent = [NSString stringWithFormat:@"%.2f %%",percent];
        NSString *stotalUsedSpace = [NSString stringWithFormat:@"%.3f GB",totalUsedSpace/(1024.0 *1024.0 * 1024.0 )];
        
        if (totalUsedSpace >= terabyte)
            stotalUsedSpace = [NSString stringWithFormat:@"%.0f Tb",totalUsedSpace/(1024*1024*1024*1024)];
        else  if (totalUsedSpace >= (1024*1024*1024))
            stotalUsedSpace = [NSString stringWithFormat:@"%.0f Gb",totalUsedSpace/(1024*1024*1024)];
        else  if (totalUsedSpace >= (1024*1024))
             stotalUsedSpace = [NSString stringWithFormat:@"%.0f Mb",totalUsedSpace/(1024*1024)];
         
        NSString *displayString = [NSString stringWithFormat:@"%@%@%@%@", stotalUsedSpace, @" out of ", stotalSpace, @" used"];
        
        
    } else {
        // log error here
    }
    
    
    return totalFreeSpace;
}

Get Disk ID


-(void) getDiskID {
    FILE *f;
    char info[256];
    NSString *serialID = NULL;
    
    f = popen("/usr/sbin/diskutil info disk0 | grep \"Media Name\"", "r");
    if (f == NULL) {
        perror("Failed to run diskutil");
        exit(0);
    }

    while (fgets(info, sizeof(info), f) != NULL) {
        serialID = @(info);
    }
    NSString *extract = [serialID substringWithRange:NSMakeRange( 30, serialID.length-30)];
    NSString *result = [extract stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    pclose(f);

   
}

Get Total RAM


-(void) getTotalRAM {
    int mib [] = { CTL_HW, HW_MEMSIZE };
    int64_t value = 0;
    size_t length = sizeof(value);

    if(-1 == sysctl(mib, 2, &value, &length, NULL, 0)) {
        
    } else {
        float terabyte =1024.0 * 1024.0 * 1024.0 * 1024.0;
        float gigabyte =1024.0 * 1024.0 * 1024.0;
        NSString *ram = NULL;
        
        if (value >= terabyte)
           ram = [NSString stringWithFormat:@"%.0f Tb",value/terabyte];
        else  if (value >= gigabyte)
           ram = [NSString stringWithFormat:@"%.0f Gb",value/gigabyte];
        
        
        
    }
      
}

Get Model Name


-(void) getModelName {
    size_t len = 0;
    NSString *model_ns = NULL;
    sysctlbyname("hw.model", NULL, &len, NULL, 0);

    if (len)
    {
        char *model = malloc(len * sizeof(char));
        sysctlbyname("hw.model", model, &len, NULL, 0);
       
        model_ns = [NSString stringWithUTF8String:model];
        free(model);
         
      
    }
}

Get Serial Number


- (void )getSerialNumber
{
    NSString *serial = nil;
    io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault,
                                     IOServiceMatching("IOPlatformExpertDevice"));
    if (platformExpert) {
        CFTypeRef serialNumberAsCFString =
        IORegistryEntryCreateCFProperty(platformExpert,
                                        CFSTR(kIOPlatformSerialNumberKey),
                                        kCFAllocatorDefault, 0);
        if (serialNumberAsCFString) {
            serial = CFBridgingRelease(serialNumberAsCFString);
        }

        IOObjectRelease(platformExpert);
        
        
    }
    
}

Get Processor Name



-(void) getProcessorName{
    FILE *f;
    char info[10000];
    NSString *processor = NULL;
    
    f = popen("/usr/sbin/system_profiler SPHardwareDataType| grep \"Processor Name:\"", "r");
    if (f == NULL) {
        perror("Failed to run system_profiler");
        exit(0);
    }

    while (fgets(info, sizeof(info), f) != NULL) {
        processor = @(info);
    }
    NSString *extract = [processor substringWithRange:NSMakeRange( 21, processor.length-21)];
    NSString *result = [extract stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    pclose(f);

    
}

Get Graphics Card Name


-(void) getGraphicsName{
     
    FILE *f;
    char info[10000];
    NSString *graphics = NULL;
    
    f = popen("/usr/sbin/system_profiler SPDisplaysDataType| grep \"Chipset Model:\"", "r");
    if (f == NULL) {
        perror("Failed to run system_profiler");
        exit(0);
    }

    while (fgets(info, sizeof(info), f) != NULL) {
        graphics = @(info);
    }
    NSString *extract = [graphics substringWithRange:NSMakeRange( 21, graphics.length-21)];
    NSString *result = [extract stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    pclose(f);

     
}

Get OS Name


-(void) getOSName{
   #define contains(str1, str2) ([str1 rangeOfString: str2 ].location != NSNotFound)
    FILE *f;
    char info[10000];
    NSString *os = NULL;
    NSString *osName = NULL;
    NSString *osVersion = NULL;
    NSString *osBuild = NULL;
    
    f = popen("sw_vers | grep \"ProductVersion\"", "r");
    if (f == NULL) {
        perror("Failed to run sw_vers");
        exit(0);
    }

    while (fgets(info, sizeof(info), f) != NULL) {
        os = @(info);
    }
    NSString *extract = [os substringWithRange:NSMakeRange( 15, os.length-15)];
    NSString *result = [extract stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    pclose(f);

    osVersion = result;
    
    if (contains(result, @"10.15"))
        osName = @"macOS Catalina";
    else if (contains(result, @"10.14"))
        osName = @"macOS Mojave";
    else if (contains(result, @"10.13"))
        osName = @"macOS High Sierra";
    else if (contains(result, @"10.12"))
        osName = @"macOS Sierra";
    else if (contains(result, @"10.11"))
        osName = @"macOS El Capitan";
    else if (contains(result, @"10.10"))
        osName = @"macOS Yosemite";
    else if (contains(result, @"10.9"))
        osName = @"macOS Mavericks";
    else  if (contains(result, @"10.8"))
        osName = @"macOS Mountain Lion";
    else if (contains(result, @"10.7"))
        osName = @"macOS Lion";
    else if (contains(result, @"10.6"))
        osName = @"macOS Snow Leopard";
    else if (contains(result, @"10.5"))
        osName = @"macOS Leopard";
    else if (contains(result, @"10.4"))
        osName = @"macOS Tiger";
    else if (contains(result, @"10.3"))
        osName = @"macOS Panther";
   else  if (contains(result, @"10.2"))
        osName = @"macOS Jaguar";
   else  if (contains(result, @"10.1"))
        osName = @"macOS Puma";
    else if (contains(result, @"10.0"))
        osName = @"macOS Cheetah";
    
   
   f = popen("sw_vers | grep \"BuildVersion\"", "r");
   if (f == NULL) {
       perror("Failed to run sw_vers");
       exit(0);
   }

   while (fgets(info, sizeof(info), f) != NULL) {
       os = @(info);
   }
   NSString *extract2 = [os substringWithRange:NSMakeRange( 14, os.length-14)];
   NSString *result2 = [extract2 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
   pclose(f);
   osBuild = result2;
  
    NSString *displayString = [NSString stringWithFormat:@"%@%@%@%@%@%@", osName, @" ", osVersion, @"(", osBuild, @")"];
     
}

Header Files

You need to include the following headers in your code for the above functions to work:


#include <sys/mount.h>
#import <sys/sysctl.h>

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.