MacOSX开发object-c获取UUID、SerialNumber方法

各种找,整理出来,备用

UUID:

 

- (NSString *)getUUID
{
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/usr/sbin/ioreg"];
    
    //ioreg -rd1 -c IOPlatformExpertDevice | grep -E '(UUID)'
    
    NSArray *arguments;
    arguments = [NSArray arrayWithObjects: @"-rd1", @"-c",@"IOPlatformExpertDevice",nil];
    [task setArguments: arguments];
    
    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    
    NSFileHandle *file;
    file = [pipe fileHandleForReading];
    
    [task launch];
    
    NSData *data;
    data = [file readDataToEndOfFile];
    
    NSString *string;
    string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    
    //NSLog (@"grep returned:n%@", string);
    
    NSString *key = @"IOPlatformUUID";
    NSRange range = [string rangeOfString:key];
    
    NSInteger location = range.location + [key length] + 5;
    NSInteger length = 32 + 4;
    range.location = location;
    range.length = length;
    
    NSString *UUID = [string substringWithRange:range];
    
    
    UUID = [UUID stringByReplacingOccurrencesOfString:@"-" withString:@""];
    //NSLog(@"UIID:%@",UUID);
    
    return UUID;
}

SerialNumber:

 

-(NSString *) getHardwareSerialNumber
{
    NSString * ret = nil;
    io_service_t platformExpert ;
    platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice")) ;
    
    if (platformExpert) {
        CFTypeRef uuidNumberAsCFString = IORegistryEntryCreateCFProperty(platformExpert, CFSTR("IOPlatformSerialNumber"), kCFAllocatorDefault, 0) ;
        if (uuidNumberAsCFString)   {
            ret = CFBridgingRelease(uuidNumberAsCFString);
            CFRelease(uuidNumberAsCFString); uuidNumberAsCFString = NULL;
        }
        IOObjectRelease(platformExpert); platformExpert = 0;
    }
    
    return ret;
}

 

 


 

你可能感兴趣的:(iOS)