2011-05-03 143 views
25

在iPhone上,我可以使用Mac的唯一標識符?

[[UIDevice currentDevice] uniqueIdentifier]; 

得到識別該設備的字符串。在OSX中有什麼相同的東西?我沒有找到任何東西。我只想確定啓動應用程序的Mac。你可以幫我嗎 ?

+1

檢查此問題:http://stackoverflow.com/questions/933460/unique-hardware-id-in-mac-os-x – Vladimir 2011-05-03 11:23:56

+0

有一個投票和Swift 2更新的答案。 ;-) – 2015-11-21 15:25:09

回答

29

Apple有一個technote關於唯一標識一個mac。下面是蘋果公司發佈了該技術說明代碼的一個鬆散的修改版本......別忘了你的項目對IOKit.framework爲了建立這個鏈接:

#import <IOKit/IOKitLib.h> 

- (NSString *)serialNumber 
{ 
    io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, 

    IOServiceMatching("IOPlatformExpertDevice")); 
    CFStringRef serialNumberAsCFString = NULL; 

    if (platformExpert) { 
     serialNumberAsCFString = IORegistryEntryCreateCFProperty(platformExpert, 
                 CFSTR(kIOPlatformSerialNumberKey), 
                  kCFAllocatorDefault, 0); 
     IOObjectRelease(platformExpert); 
    } 

    NSString *serialNumberAsNSString = nil; 
    if (serialNumberAsCFString) { 
     serialNumberAsNSString = [NSString stringWithString:(NSString *)serialNumberAsCFString]; 
     CFRelease(serialNumberAsCFString); 
    } 

    return serialNumberAsNSString; 
} 
+0

謝謝你的回答我會試試看。我還沒有和IOKit一起工作。但會看看它。 – 2011-05-03 13:04:37

+0

太棒了!我還沒有真正理解代碼。但它給了我一個序列號。謝謝! – 2011-05-04 10:44:02

+1

不幸的是,該解決方案不能在64位模式下工作。也許你對這個問題有所瞭解? – xyz 2012-02-24 10:34:27

1

感謝。作品改變

serialNumberAsNSString = [NSString stringWithString:(NSString *)serialNumberAsCFString]; 

TO

serialNumberAsNSString = [NSString stringWithString:(__bridge NSString *)serialNumberAsCFString]; 

的__bridge後完全是由它本身的Xcode建議。

16

斯威夫特2回答

這樣的回答增強賈勒特哈迪2011年的答案。這是一個Swift 2字符串擴展。我已經添加了內聯註釋來解釋我做了什麼以及爲什麼,因爲導航對象是否需要發佈可能會非常棘手。

extension String { 

    static func macSerialNumber() -> String { 

     // Get the platform expert 
     let platformExpert: io_service_t = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice")); 

     // Get the serial number as a CFString (actually as Unmanaged<AnyObject>!) 
     let serialNumberAsCFString = IORegistryEntryCreateCFProperty(platformExpert, kIOPlatformSerialNumberKey, kCFAllocatorDefault, 0); 

     // Release the platform expert (we're responsible) 
     IOObjectRelease(platformExpert); 

     // Take the unretained value of the unmanaged-any-object 
     // (so we're not responsible for releasing it) 
     // and pass it back as a String or, if it fails, an empty string 
     return (serialNumberAsCFString.takeUnretainedValue() as? String) ?? "" 

    } 

} 

另外,該功能可以返回String?和最後一行可以返回一個空字符串。這樣可以更容易地識別無法檢索序列號的極端情況(例如,在Jerret的回答中提到的修復的Mac主板場景哈里斯)。

我還驗證了儀器的正確內存管理。

我希望有人認爲它有用!

+0

很好的回答,謝謝! – 2016-02-28 11:05:55