每次呼叫 CFUUIDCreate,系統都會返回一個全新的唯一 ID。若想永久保存這個 ID,就必須自己處理:先取一次並存進 NSUserDefaults、Keychain、Pasteboard 等處,下次再從中取出。
- (NSString *)createUUID {
CFUUIDRef uuid = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
return (__bridge NSString *)string;
}NSString *uuid = [[NSUUID UUID] UUIDString];
與 CFUUID 相同,每次呼叫 NSUUID 都會得到一個新的 UUID,需要自己妥善保存。
NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
advertisingIdentifier 由系統維持唯一性,同一裝置上所有 App 取到的值都相同。但有兩種情況會改變它:重置系統(設定 -> 通用 -> 還原 -> 抹掉所有內容和設定),或重置廣告標識符(設定 -> 隱私 -> 廣告 -> 還原廣告標識符)。這兩種情況下都會產生新的 advertisingIdentifier,因此仍無法保證裝置唯一。
NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
蘋果官方文檔的說明:
只要該 App(或同一開發商的另一個 App)仍安裝在此 iOS 裝置上,此屬性的值就保持不變。當使用者刪除該開發商的所有 App 後又重新安裝其中一個或多個,值就會改變。此外,透過 Xcode 安裝測試版本或以 ad-hoc 方式散佈時,值也可能改變。因此,若你的 App 儲存了這個值,就應該妥善處理識別碼變動的情況。
在同一裝置上,不同 vendor 的 App 取到的 IDFV 並不相同;而同一 vendor 下的不同 App 取到的 IDFV 則相同。但如果使用者刪除了這個 vendor 的所有 App 再重新安裝,IDFV 就會被重置,與先前不同,因此也非裝置唯一。
什麼是 Vendor?一個 Vendor 是 CFBundleIdentifier(應用標識符)的前綴,如下:

舉例來說,com.doubleencore.app1 與 com.doubleencore.app2 會取到相同的 IDFV,因為它們共享 com.doubleencore 前綴;而 com.massivelyoverrated 與 net.doubleencore 取到的則不相同。
以上所有 ID 都無法保證裝置唯一,那有沒有更可靠的方式?
以 IDFV 為例,為了讓使用者在刪除 App 後仍能取到相同的 IDFV,可以借助 Keychain。使用 SAMKeychain 能很方便地操作 keychain。需要注意的是,keychain 在同一個蘋果帳號的不同裝置間是同步的,因此要設定 query.synchronizationMode = SAMKeychainQuerySynchronizationModeNo;,讓這個值不在裝置間同步,如此不同裝置取到的便是不同的 ID。程式碼如下:
-(NSString *)getUniqueDeviceIdentifierAsString {
NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey];
NSString *strApplicationUUID = [SAMKeychain passwordForService:appName account:@"incoding"];
if (strApplicationUUID == nil) {
strApplicationUUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSError *error = nil;
SAMKeychainQuery *query = [[SAMKeychainQuery alloc] init];
query.service = appName;
query.account = @"incoding";
query.password = strApplicationUUID;
query.synchronizationMode = SAMKeychainQuerySynchronizationModeNo;
[query save:&error];
}
return strApplicationUUID;
}參考資料:
The Developer's Guide to Unique Identifiers
How to preserve identifierForVendor in ios after uninstalling ios app on device?
What's the difference between UUID, GUID and UDID?
文章轉自 yanging的簡書