1. 程式人生 > >如何獲取不變的UDID

如何獲取不變的UDID

一、iOS不用版本獲取UDID的方法比較

  1)iOS 5.0

  iOS 2.0版本以後UIDevice提供一個獲取裝置唯一識別符號的方法uniqueIdentifier,通過該方法我們可以獲取裝置的序列號,這個也是目前為止唯一可以確認唯一的標示符。好景不長,因為該唯一識別符號與手機一一對應,蘋果覺得可能會洩露使用者隱私,所以在 iOS 5.0之後該方法就被廢棄掉了。

  而且蘋果做的更狠,今年5月份以後提交App Store的產品都不允許再用uniqueIdentifier介面,甚至有些朋友因為程式碼中有UDID還被打回來,看來這條路是被封死了。

  2)iOS 6.0

  iOS 6.0系統新增了兩個用於替換uniqueIdentifier的介面,分別是:identifierForVendor,advertisingIdentifier。

  (a) identifierForVendor介面的官方文件介紹如下:

複製程式碼
The value of this property is the same for apps that come from the same vendor running on the same device. A different value is returned for apps on the same device that come from different vendors, and for apps on different devices regardless of vendor.

The value of this property may be nil if the app is running in the background, before the user has unlocked the device the first time after the device has been restarted. If the value is nil, wait and get the value again later.

The value in this property remains the same while the app (or another app from the same vendor) is installed on the iOS device. The value changes when the user deletes all of that vendor’s apps from the device and subsequently reinstalls one or more of them. Therefore, if your app stores the value of this property anywhere, you should gracefully handle situations where the identifier changes.
複製程式碼

  大概意思就是“同一開發商的APP在指定機器上都會獲得同一個ID。當我們刪除了某一個裝置上某個開發商的所有APP之後,下次獲取將會獲取到不同的ID。” 也就是說我們通過該介面不能獲取用來唯一標識裝置的ID,問題總是難不倒聰明的程式設計師,於是大家想到了使用WiFi的mac地址來取代已經廢棄了的uniqueIdentifier方法。具體的方法晚上有很多,大家感興趣的可以自己找找,這兒提供一個網址: http://stackoverflow.com/questions/677530/how-can-i-programmatically-get-the-mac-address-of-an-iphone

      (b) advertisingIdentifier

advertisingIdentifier俗稱廣告ID,IDFA。它只能用於廣告服務的程式,也就是在提交稽核時,需要新增廣告支援,負責會被Apple拒審,這是一大限制。比如在開發SDK時,使用這個值就得慎重,因為你不知道整合你的APP是否會支援廣告服務。

另外在永續性方面,也有一些限制。當用戶還原系統設定或者還原廣告識別符號時,會重置此值;另外使用者開啟"限制廣告跟蹤"後,這個值雖然能拿到,但是已經被重置了。

正常開啟廣告跟蹤:

限制廣告跟蹤:

開啟廣告跟蹤:

限制廣告跟蹤:

由上可見,每次獲取的id值都是不一樣的,相當於都重置了。

  3)iOS 7.0  

  iOS 7中蘋果再一次無情的封殺mac地址,使用之前的方法獲取到的mac地址全部都變成了02:00:00:00:00:00。有問題總的解決啊,於是四處查資料,終於有了思路是否可以使用KeyChain來儲存獲取到的唯一標示符呢,這樣以後即使APP刪了再裝回來,也可以從KeyChain中讀取回來。

二、KeyChain介紹

   我們搞iOS開發,一定都知道OS X裡面的KeyChain(鑰匙串),通常要鄉鎮及除錯的話,都得安裝證書之類的,這些證書就是儲存在KeyChain中,還有我們平時瀏覽網頁記錄的賬號密碼也都是記錄在KeyChain中。iOS中的KeyChain相比OS X比較簡單,整個系統只有一個KeyChain,每個程式都可以往KeyChain中記錄資料,而且只能讀取到自己程式記錄在KeyChain中的資料。iOS中Security.framework框架提供了四個主要的方法來操作KeyChain:

複製程式碼
// 查詢
OSStatus SecItemCopyMatching(CFDictionaryRef query, CFTypeRef *result);

// 新增
OSStatus SecItemAdd(CFDictionaryRef attributes, CFTypeRef *result);

// 更新KeyChain中的Item
OSStatus SecItemUpdate(CFDictionaryRef query, CFDictionaryRef attributesToUpdate);

// 刪除KeyChain中的Item
OSStatus SecItemDelete(CFDictionaryRef query)
複製程式碼

  這四個方法引數比較複雜,一旦傳錯就會導致操作KeyChain失敗,這塊兒文件中介紹的比較詳細,大家可以查查官方文件Keychain Services Reference

  前面提到了每個APP只允許訪問自己在KeyChain中記錄的資料,那麼是不是就沒有別的辦法訪問其他APP存在KeyChain的資料了?

  蘋果提供了一個方法允許同一個發商的多個APP訪問各APP之間的途徑,即在調SecItemAdd新增資料的時候指定AccessGroup,即訪問組。一個APP可以屬於同事屬於多個分組,新增KeyChain資料訪問組需要做一下兩件事情:

  a、在APP target的bulibSetting裡面設定Code Signing Entitlements,指向包含AceessGroup的分組資訊的plist檔案。該檔案必須和工程檔案在同一個目錄下,我在新增訪問分組的時候就因為plist檔案位置問題,操作KeyChain失敗,查詢這個問題還花了好久的時間。

  b、在工程目錄下新建一個KeychainAccessGroups.plist檔案,該檔案的結構中最頂層的節點必須是一個名為“keychain-access-groups”的Array,並且該Array中每一項都是一個描述分組的NSString。對於String的格式也有相應要求,格式為:"AppIdentifier.com.***",其中APPIdentifier就是你的開發者帳號對應的ID。

  c、在程式碼中往KeyChain中Add資料的時候,設定kSecAttrAccessGroup,程式碼如下:

複製程式碼
   NSString *accessGroup = [NSString stringWithUTF8String:"APPIdentifier.com.cnblogs.smileEvday"];
    if (accessGroup != nil)
    {
#if TARGET_IPHONE_SIMULATOR
        // Ignore the access group if running on the iPhone simulator.
        //
        // Apps that are built for the simulator aren't signed, so there's no keychain access group
        // for the simulator to check. This means that all apps can see all keychain items when run
        // on the simulator.
        //
        // If a SecItem contains an access group attribute, SecItemAdd and SecItemUpdate on the
        // simulator will return -25243 (errSecNoAccessForItem).
#else
        [dictForQuery setObject:accessGroup forKey:(id)kSecAttrAccessGroup];
#endif
    }
複製程式碼

  這段程式碼是從官方的Demo中直接拷貝過來的,根據註釋我們可以看到,模擬器是不支援AccessGroup的,所以才行了預編譯巨集來選擇性新增。

  注:appIdentifer就是開發者帳號的那一串標識,如下圖所示:

   

  開啟xcode的Organizer,選擇Device選項卡,連線裝置就可以看到裝置上安裝的開發者賬號描述檔案列表,其中第五列最開始的10個字元即為App Identifier,這塊兒前面寫的不是很清楚,好多朋友加我qq問我,今天特地補上。

三、使用KeyChain儲存和獲取UDID

  說了這麼多終於進入正題了,如何在iOS 7上面獲取到不變的UDID。我們將第二部分所講的知識直接應用進來就可以了輕鬆達到我們要的效果了,下面我們先看看往如何將獲取到的identifierForVendor新增到KeyChain中的程式碼。

複製程式碼
+ (BOOL)settUDIDToKeyChain:(NSString*)udid
{
    NSMutableDictionary *dictForAdd = [[NSMutableDictionary alloc] init];
    
    [dictForAdd setValue:(id)kSecClassGenericPassword forKey:(id)kSecClass];
    [dictForAdd setValue:[NSString stringWithUTF8String:kKeychainUDIDItemIdentifier] forKey:kSecAttrDescription];
    
    [dictForAdd setValue:@"UUID" forKey:(id)kSecAttrGeneric];
    
    // Default attributes for keychain item.
    [dictForAdd setObject:@"" forKey:(id)kSecAttrAccount];
    [dictForAdd setObject:@"" forKey:(id)kSecAttrLabel];
    
    // The keychain access group attribute determines if this item can be shared
    // amongst multiple apps whose code signing entitlements contain the same keychain access group.
    NSString *accessGroup = [NSString stringWithUTF8String:kKeyChainUDIDAccessGroup];
    if (accessGroup != nil)
    {
#if TARGET_IPHONE_SIMULATOR
        // Ignore the access group if running on the iPhone simulator.
        //
        // Apps that are built for the simulator aren't signed, so there's no keychain access group
        // for the simulator to check. This means that all apps can see all keychain items when run
        // on the simulator.
        //
        // If a SecItem contains an access group attribute, SecItemAdd and SecItemUpdate on the
        // simulator will return -25243 (errSecNoAccessForItem).
#else
        [dictForAdd setObject:accessGroup forKey:(id)kSecAttrAccessGroup];
#endif
    }

    const char *udidStr = [udid UTF8String];
    NSData *keyChainItemValue = [NSData dataWithBytes:udidStr length:strlen(udidStr)];
    [dictForAdd setValue:keyChainItemValue forKey:(id)kSecValueData];
    
    OSStatus writeErr = noErr;
    if ([SvUDIDTools getUDIDFromKeyChain]) {        // there is item in keychain
        [SvUDIDTools updateUDIDInKeyChain:udid];
        [dictForAdd release];
        return YES;
    }
    else {          // add item to keychain
        writeErr = SecItemAdd((CFDictionaryRef)dictForAdd, NULL);
        if (writeErr != errSecSuccess) {
            NSLog(@"Add KeyChain Item Error!!! Error Code:%ld", writeErr);
            
            [dictForAdd release];
            return NO;
        }
        else {
            NSLog(@"Add KeyChain Item Success!!!");
            [dictForAdd release];
            return YES;
        }
    }
    
    [dictForAdd release];
    return NO;
}
複製程式碼

  上面程式碼中,首先構建一個要新增到KeyChain中資料的Dictionary,包含一些基本的KeyChain Item的資料型別,描述,訪問分組以及最重要的資料等資訊,最後通過呼叫SecItemAdd方法將我們需要儲存的UUID儲存到KeyChain中。

  獲取KeyChain中相應資料的程式碼如下:

複製程式碼
+ (NSString*)getUDIDFromKeyChain
{
    NSMutableDictionary *dictForQuery = [[NSMutableDictionary alloc] init];
    [dictForQuery setValue:(id)kSecClassGenericPassword forKey:(id)kSecClass];
    
    // set Attr Description for query
    [dictForQuery setValue:[NSString stringWithUTF8String:kKeychainUDIDItemIdentifier]
                    forKey:kSecAttrDescription];
    
    // set Attr Identity for query
    NSData *keychainItemID = [NSData dataWithBytes:kKeychainUDIDItemIdentifier
                                            length:strlen(kKeychainUDIDItemIdentifier)];
    [dictForQuery setObject:keychainItemID forKey:(id)kSecAttrGeneric];
    
    // The keychain access group attribute determines if this item can be shared
    // amongst multiple apps whose code signing entitlements contain the same keychain access group.
    NSString *accessGroup = [NSString stringWithUTF8String:kKeyChainUDIDAccessGroup];
    if (accessGroup != nil)
    {
#if TARGET_IPHONE_SIMULATOR
        // Ignore the access group if running on the iPhone simulator.
        //
        // Apps that are built for the simulator aren't signed, so there's no keychain access group
        // for the simulator to check. This means that all apps can see all keychain items when run
        // on the simulator.
        //
        // If a SecItem contains an access group attribute, SecItemAdd and SecItemUpdate on the
        // simulator will return -25243 (errSecNoAccessForItem).
#else
        [dictForQuery setObject:accessGroup forKey:(id)kSecAttrAccessGroup];
#endif
    }
    
    [dictForQuery setValue:(id)kCFBooleanTrue forKey:(id)kSecMatchCaseInsensitive];
    [dictForQuery setValue:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    [dictForQuery setValue:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    
    OSStatus queryErr   = noErr;
    NSData   *udidValue = nil;
    NSString *udid      = nil;
    queryErr = SecItemCopyMatching((CFDictionaryRef)dictForQuery, (CFTypeRef*)&udidValue);
    
    NSMutableDictionary *dict = nil;
    [dictForQuery setValue:(id)kCFBooleanTrue forKey:(id)kSecReturnAttributes];
    queryErr = SecItemCopyMatching((CFDictionaryRef)dictForQuery, (CFTypeRef*)&dict);
    
    if (queryErr == errSecItemNotFound) {
        NSLog(@"KeyChain Item: %@ not found!!!", [NSString stringWithUTF8String:kKeychainUDIDItemIdentifier]);
    }
    else if (queryErr != errSecSuccess) {
        NSLog(@"KeyChain Item query Error!!! Error code:%ld", queryErr);
    }
    if (queryErr == errSecSuccess) {
        NSLog(@"KeyChain Item: %@", udidValue);
        
        if (udidValue) {
            udid = [NSString stringWithUTF8String:udidValue.bytes];
        }
    }
    
    [dictForQuery release];
    return udid;
}
複製程式碼

  上面程式碼的流程也差不多一樣,首先建立一個Dictionary,其中設定一下查詢條件,然後通過SecItemCopyMatching方法獲取到我們之前儲存到KeyChain中的資料。

四、總結

  本文介紹了使用KeyChain實現APP刪除後依然可以獲取到相同的UDID資訊的解決方法,當系統升級後也是獲取到相同的UDID,但是刷機、系統還原都會清除keychain裡的資訊。