您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

iOS 取得 UUID 並用 Keychain 保存的實作教學

編輯:iOS 7 技巧

UUID 是 iOS 開發者在真機測試時經常需要處理的識別碼。本文示範如何取得 UUID,並用 Keychain 保存,讓 App 即使被刪除後重裝,仍能拿到同一組識別碼。

為什麼要用 Keychain 而不是 NSUserDefaults

UDID 已被蘋果棄用,改以 UUID 作為裝置的唯一標識。但如果用 NSUserDefaults 保存,使用者刪除 App 再重裝時,NSUserDefaults 也會被清空,取回的 UUID 就變成新的一組。改用 Keychain 保存可以避開這個問題,讓卸載重裝後的 UUID 維持不變。

需要說明的是,若使用者重新刷機或升級系統,Keychain 內容仍可能改變,UUID 也會跟著變。不過以目前公開的 API 而言,這已經是最可行的折衷方案。

UUID.h

#import 尖括號(Foundation/Foundation.h)

@interface UUID : NSObject
+(NSString *)getUUID;
@end

UUID.m

#import "UUID.h"
#import 尖括號(Foundation/Foundation.h)
#import "KeychainItemWrapper.h"

@implementation UUID
+(NSString *)getUUID
{
    KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc]
                                          initWithIdentifier:@"UUID"
                                          accessGroup:@"YOUR_BUNDLE_SEED.com.yourcompany.userinfo"];

    NSString *strUUID = [keychainItem objectForKey:(id)CFBridgingRelease(kSecValueData)];
    //首次執行該方法時,uuid為空
    if ([strUUID isEqualToString:@""])
    {
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        strUUID = (NSString *)CFBridgingRelease(CFUUIDCreateString (kCFAllocatorDefault,uuidRef));
        [keychainItem setObject:strUUID forKey:(id)CFBridgingRelease(kSecValueData)];
    }
    return strUUID;
}
@end

KeychainItemWrapper

第二個類別來自蘋果官方範例程式中對 Keychain 的封裝,也可直接從官方 GenericKeychain 範例下載原始碼。

KeychainItemWrapper.h

#import 尖括號(UIKit/UIKit.h)

@interface KeychainItemWrapper : NSObject
{
    NSMutableDictionary *keychainItemData;
    NSMutableDictionary *genericPasswordQuery;
}
@property (nonatomic, retain) NSMutableDictionary *keychainItemData;
@property (nonatomic, retain) NSMutableDictionary *genericPasswordQuery;
- (id)initWithIdentifier: (NSString *)identifier accessGroup:(NSString *) accessGroup;
- (void)setObject:(id)inObject forKey:(id)key;
- (id)objectForKey:(id)key;
- (void)resetKeychainItem;
@end

KeychainItemWrapper.m

#import "KeychainItemWrapper.h"
#import 尖括號(Security/Security.h)

@interface KeychainItemWrapper (PrivateMethods)
- (NSMutableDictionary *)secItemFormatToDictionary:(NSDictionary *)dictionaryToConvert;
- (NSMutableDictionary *)dictionaryToSecItemFormat:(NSDictionary *)dictionaryToConvert;
- (void)writeToKeychain;
@end

@implementation KeychainItemWrapper
@synthesize keychainItemData, genericPasswordQuery;

- (id)initWithIdentifier: (NSString *)identifier accessGroup:(NSString *) accessGroup;
{
    if (self = [super init])
    {
        genericPasswordQuery = [[NSMutableDictionary alloc] init];

        [genericPasswordQuery setObject:(id)CFBridgingRelease(kSecClassGenericPassword) forKey:(id)kSecClass];
        [genericPasswordQuery setObject:identifier forKey:(id)CFBridgingRelease(kSecAttrGeneric)];

        if (accessGroup != nil)
        {
#if TARGET_IPHONE_SIMULATOR
#else
            [genericPasswordQuery setObject:accessGroup forKey:(id)kSecAttrAccessGroup];
#endif
        }

        [genericPasswordQuery setObject:(id)CFBridgingRelease(kSecMatchLimitOne) forKey:(id)kSecMatchLimit];
        [genericPasswordQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnAttributes];

        NSDictionary *tempQuery = [NSDictionary dictionaryWithDictionary:genericPasswordQuery];

        NSMutableDictionary *outDictionary = nil;

        if (! SecItemCopyMatching((CFDictionaryRef)tempQuery, (CFTypeRef *)&outDictionary) == noErr)
        {
            [self resetKeychainItem];

            [keychainItemData setObject:identifier forKey:(id)kSecAttrGeneric];
            if (accessGroup != nil)
            {
#if TARGET_IPHONE_SIMULATOR
#else
                [keychainItemData setObject:accessGroup forKey:(id)kSecAttrAccessGroup];
#endif
            }
        }
        else
        {
            self.keychainItemData = [self secItemFormatToDictionary:outDictionary];
        }

        [outDictionary release];
    }

    return self;
}

- (void)dealloc
{
    [keychainItemData release];
    [genericPasswordQuery release];
    [super dealloc];
}

- (void)setObject:(id)inObject forKey:(id)key
{
    if (inObject == nil) return;
    id currentObject = [keychainItemData objectForKey:key];
    if (![currentObject isEqual:inObject])
    {
        [keychainItemData setObject:inObject forKey:key];
        [self writeToKeychain];
    }
}

- (id)objectForKey:(id)key
{
    return [keychainItemData objectForKey:key];
}

- (void)resetKeychainItem
{
    OSStatus junk = noErr;
    if (!keychainItemData)
    {
        self.keychainItemData = [[NSMutableDictionary alloc] init];
    }
    else if (keychainItemData)
    {
        NSMutableDictionary *tempDictionary = [self dictionaryToSecItemFormat:keychainItemData];
        junk = SecItemDelete((CFDictionaryRef)tempDictionary);
        NSAssert( junk == noErr || junk == errSecItemNotFound, @"Problem deleting current dictionary." );
    }

    [keychainItemData setObject:@"" forKey:(id)kSecAttrAccount];
    [keychainItemData setObject:@"" forKey:(id)kSecAttrLabel];
    [keychainItemData setObject:@"" forKey:(id)kSecAttrDescription];
    [keychainItemData setObject:@"" forKey:(id)kSecValueData];
}

- (NSMutableDictionary *)dictionaryToSecItemFormat:(NSDictionary *)dictionaryToConvert
{
    NSMutableDictionary *returnDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionaryToConvert];
    [returnDictionary setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass];
    NSString *passwordString = [dictionaryToConvert objectForKey:(id)kSecValueData];
    [returnDictionary setObject:[passwordString dataUsingEncoding:NSUTF8StringEncoding] forKey:(id)kSecValueData];

    return returnDictionary;
}

- (NSMutableDictionary *)secItemFormatToDictionary:(NSDictionary *)dictionaryToConvert
{
    NSMutableDictionary *returnDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionaryToConvert];
    [returnDictionary setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [returnDictionary setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass];
    NSData *passwordData = NULL;
    if (SecItemCopyMatching((CFDictionaryRef)returnDictionary, (CFTypeRef *)&passwordData) == noErr)
    {
        [returnDictionary removeObjectForKey:(id)kSecReturnData];
        NSString *password = [[[NSString alloc] initWithBytes:[passwordData bytes] length:[passwordData length]
                                                     encoding:NSUTF8StringEncoding] autorelease];
        [returnDictionary setObject:password forKey:(id)kSecValueData];
    }
    else
    {
        NSAssert(NO, @"Serious error, no matching item found in the keychain.\n");
    }

    [passwordData release];

    return returnDictionary;
}

- (void)writeToKeychain
{
    NSDictionary *attributes = NULL;
    NSMutableDictionary *updateItem = NULL;
    OSStatus result;

    if (SecItemCopyMatching((CFDictionaryRef)genericPasswordQuery, (CFTypeRef *)&attributes) == noErr)
    {
        updateItem = [NSMutableDictionary dictionaryWithDictionary:attributes];
        [updateItem setObject:[genericPasswordQuery objectForKey:(id)kSecClass] forKey:(id)kSecClass];
        NSMutableDictionary *tempCheck = [self dictionaryToSecItemFormat:keychainItemData];
        [tempCheck removeObjectForKey:(id)kSecClass];

#if TARGET_IPHONE_SIMULATOR
        [tempCheck removeObjectForKey:(id)kSecAttrAccessGroup];
#endif
        result = SecItemUpdate((CFDictionaryRef)updateItem, (CFDictionaryRef)tempCheck);
        NSAssert( result == noErr, @"Couldn't update the Keychain Item." );
    }
    else
    {
        result = SecItemAdd((CFDictionaryRef)[self dictionaryToSecItemFormat:keychainItemData], NULL);
        NSAssert( result == noErr, @"Couldn't add the Keychain Item." );
    }
}

@end

幾個實作注意事項

1. KeychainItemWrapper 類別在官方範例中也有提供,若複製時出錯,可直接從上面提到的官方範例下載。

2. 使用時必須在專案中加入 Security.framework。

3. 最容易被忽略的是 accessGroup 的設定,也就是下面這段初始化程式:

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

(1)在與專案相同目錄下建立 KeychainAccessGroups.plist 檔。

檔案結構最外層必須是一個名為 "keychain-access-groups" 的 Array,且其中每一項都是描述分組的 NSString。YOUR_BUNDLE_SEED.com.yourcompany.userinfo 就是要設定為組名的字串。

(2)在 Target 的 Build Settings 中,找到 Code Signing 欄位,於 Code Signing Entitlements 右側填入 KeychainAccessGroups.plist。

完成以上設定後即可測試。

測試程式碼與結果

NSString * uuid= [UUID getUUID];
NSLog(@"uuid=%@",uuid);

輸出結果:

uuid=19AAB430-9CB8-4325-ACC5-D7D386B68960

首次安裝時印出一組 uuid,把 App 刪除後重新安裝,再次呼叫 getUUID 印出的結果與先前完全相同,即代表設定成功。

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