简体   繁体   中英

How to get UUID in Mac OS X Programming

I am trying to access Mac OS X UUID in cocoa programming using this code.

NSString *uuid = [[NSUUID UUID] UUIDString];

here uuid returns a unique id every time whenever I am accessing uuid, it keeps changing even I am not reinstalling app .I need to know how to access UUID in Mac OS X which will be same whether I am reinstalling app or recompiling, it should remain same.

In Ios i am able to achieve the same by below code.

NSString *iosuuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];

Here iosuuid returns uuid which will remain same even when I am reinstalling and recompiling my app.

Don't suggest me to use Mac address, which I don't want to access for some purpose in my app.

In case somebody runs into this question looking for simple Objective-C solution - implementation like below worked for me (tested on macOS 11.2):

#import <IOKit/IOKitLib.h>

- (NSString *) getUUID {
    io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault,IOServiceMatching("IOPlatformExpertDevice"));
    if (!platformExpert) return nil;

    CFTypeRef serialNumberAsCFString = IORegistryEntryCreateCFProperty(platformExpert,CFSTR(kIOPlatformUUIDKey),kCFAllocatorDefault, 0);
    if (!serialNumberAsCFString) return nil;

    IOObjectRelease(platformExpert);
    return (__bridge NSString *)(serialNumberAsCFString);;
}

For compiling add IOKit framework:

gcc -fobjc-arc -framework Cocoa -framework IOKit -x objective-c sources/** main.m -o app.bin

You can call this function with as simple as:

int main () {
    ..
    NSString *uuid = self.getUUID;
    NSLog(@"uuid: %@", uuid);
    ..
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM