iOS udid+keychain 唯一标示

我是用来标识唯一设备的,因为苹果不让用udid了,所以用的open udid的第三方一个类。

OpenUDID的类比较长就不在这里发了,需要的可以去网上下,实在搜不到可以找我要。

下面说下用keychain来存取。

参考网站:http://blog.csdn.net/sqq521/article/details/11988995。尊重原创。

 

我自己写的类如下:

头文件:

 

#import <Foundation/Foundation.h>

 

@interface Keychain : NSObject

 

+ (void)save:(NSString *)service data:(id)data;

+ (id)load:(NSString *)service;

//+ (void)delete:(NSString *)service;

 

@end

 

.m文件:

 

#import "Keychain.h"

 

@implementation Keychain

 

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {

    return [NSMutableDictionary dictionaryWithObjectsAndKeys:

            (id)kSecClassGenericPassword,(id)kSecClass,

            service, (id)kSecAttrService,

            service, (id)kSecAttrAccount,

            (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,

            nil];

}

 

+ (void)save:(NSString *)service data:(id)data {

    //Get search dictionary

    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];

    //Delete old item before add new item

    SecItemDelete((CFDictionaryRef)keychainQuery);

    //Add new object to search dictionary(Attention:the data format)

    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];

    //Add item to keychain with the search dictionary

    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);

}

 

+ (id)load:(NSString *)service {

    id ret = nil;

    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];

    //Configure the search setting

    //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue

    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];

    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];

    CFDataRef keyData = NULL;

    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {

        @try {

            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)keyData];

        } @catch (NSException *e) {

            NSLog(@"Unarchive of %@ failed: %@", service, e);

        } @finally {

        }

    }

    if (keyData)

        CFRelease(keyData);

    return ret;

}

@end

 

 

具体调用如下:

 

    NSString * const KEY_UDID = @"uuid4Pet";

    NSString * uuid = [Keychain load:KEY_UDID];

    

    NSLog(@"%@", uuid);

    if (uuid == nil || uuid.length == 0) {

        [Keychain save:KEY_UDID data:[OpenUDID value]];

    }

    

    NSLog(@"%@", [Keychain load:KEY_UDID]);

    

    [USER setObject:[Keychain load:KEY_UDID] forKey:@"UDID"];

 

USER是我定义的宏,里面是NSUserDefaults。

posted @ 2016-03-21 17:41  Show撑腰  阅读(623)  评论(0编辑  收藏  举报