iOS使用keychain和uuid确定设备唯一标识

我是用来标识唯一设备的,因为苹果不让用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。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值