如何在Mac OS X编程中获取UUID



我正在尝试使用此代码访问可可编程中的Mac OS X UUID。

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

这里,每次我访问uuid时,uuid都会返回一个唯一的id,即使我没有重新安装应用程序,它也会不断变化。我需要知道如何在Mac OS X中访问uuid,无论我是重新安装应用还是重新编译,它都应该保持不变。

在Ios中,我可以通过下面的代码来实现同样的目的。

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

这里iosuuid返回的uuid将保持不变,即使我重新安装和重新编译我的应用程序。

不要建议我使用Mac地址,我不想在应用程序中出于某种目的访问该地址。

如果有人在寻找简单的Objective-C解决方案时遇到这个问题,下面的实现对我来说很有效(在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);
IOObjectRelease(platformExpert);
if (!serialNumberAsCFString) return nil;
return (__bridge NSString *)(serialNumberAsCFString);;
}

为编译添加IOKit框架:

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

您可以用以下简单的方法调用此函数:

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

最新更新