您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

告別 UUID:用 Keychain 保存裝置識別碼的做法

編輯:iOS 相關資訊

Apple 從 2013 年 5 月 1 日起就不再允許使用 UUID 的 App 上架,因此我們需要找替代方案。常見的解法是把識別碼存進 Keychain,讓它在 App 被刪除重裝之後依然存在。

Apple 官方提供過一個名為 GenericKeychain 的範例專案,其中封裝了 KeychainItemWrapper 這個類別,把原本繁瑣的 Keychain 操作簡化了不少,可以直接拿來使用。

準備工作

先匯入 Security.framework(KeychainItemWrapper 本質上就是對 Security 的一層封裝),再把 KeychainItemWrapper.h 與 KeychainItemWrapper.m 加入專案,然後在需要的地方引入標頭檔:

#import "KeychainItemWrapper.h"

實作

下面的寫法同時兼顧了新舊邏輯:先嘗試從 Keychain 讀出既有識別碼,若不存在(代表是全新安裝)才用 identifierForVendor 產生一組並寫回去:

NSString *uuidStr = nil;

KeychainItemWrapper *keychainItem =
    [[KeychainItemWrapper alloc] initWithIdentifier:@"UUID"
                                        accessGroup:@"com.xxx.xxx"];

NSString *savedStr = [keychainItem objectForKey:(id)kSecValueData];

if (savedStr.length == 0) {
    // 首次執行,產生新的識別碼並存入 Keychain
    NSString *newStr = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [keychainItem setObject:newStr forKey:(id)kSecValueData];
    uuidStr = newStr;
} else {
    uuidStr = savedStr;
}

NSLog(@"=====%@", uuidStr);
return uuidStr;

這裡有兩點值得注意。第一,identifierForVendor 的值在「同一開發商、同一裝置」的前提下是穩定的,但使用者若把所有同開發商的 App 都刪光再重裝,它會被重置——這正是我們需要 Keychain 的原因:Keychain 裡的資料預設不會隨 App 刪除而清除。第二,accessGroup 必須與你的 provisioning 設定一致,否則存取會失敗;如果你不打算在多個 App 之間共享 Keychain 項目,這裡其實可以省略,改用不帶 accessGroup 的初始化方式即可。另外提醒,把使用者可識別的資訊寫進 Keychain 時,建議搭配 kSecAttrAccessible 設定合適的可及性層級(例如僅在裝置解鎖時可讀),避免資料在鎖屏狀態下被讀取。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved