开发中经常需要获取设备的唯一标识符,app的更新迭代,删除,系统升级等,都不会影响keychain数据中的保存(系统恢复出厂设置等,恢复型操作除外),所以Keychain显得尤为重要,
1.将Keychain Sharing按钮打开
2.
#import
@interface UUID : NSObject
+(NSString*)getUUID;
@end
#import "UUID.h"
#import "KeyChainStore.h"
@implementation UUID
+(NSString*)getUUID {
NSString *strUUID =(NSString*)[KeyChainStore load:@"com.company.app.usernamepassword"];
//首次执行该方法时,uuid为空
if([strUUID isEqualToString:@""]|| !strUUID){
//生成一个uuid的方法
CFUUIDRef uuidRef= CFUUIDCreate(kCFAllocatorDefault);
strUUID =(NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault,uuidRef));
//将该uuid保存到keychain
[KeyChainStore save:@"com.company.app.usernamepassword" data:strUUID];
}
return strUUID;
}
@end
3.
#import
@interface KeyChainStore : NSObject
+(void)save:(NSString*)service data:(id)data;
+(id)load:(NSString*)service;
+(void)deleteKeyData:(NSString*)service;
@end
#import "KeyChainStore.h"
@implementation KeyChainStore
+(NSMutableDictionary*)getKeychainQuery:(NSString*)service {
return[NSMutableDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassGenericPassword,(id)kSecClass,
service,(id)kSecAttrService,
service,(id)kSecAttrAccount,
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 searchdictionary(Attention:the data format)
[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data]forKey:(id)kSecValueData];
//Add item to keychain with the searchdictionary
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 areexpecting only a single attribute to be returned(the password)wecan 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:(__bridge NSData*)keyData];
}@catch(NSException *e){
NSLog(@"Unarchiveof %@ failed: %@",service,e);
}@finally{
}
}
if(keyData)
CFRelease(keyData);
return ret;
}
+(void)deleteKeyData:(NSString*)service {
NSMutableDictionary*keychainQuery =[self getKeychainQuery:service];
SecItemDelete((CFDictionaryRef)keychainQuery);
}
@end
4.在需要获取设备唯一标识符的地方导入以下两个头文件,再调用 [UUID getUUID]方法即可
#import "UUID.h"
#import "KeyChainStore.h"
params[@"imei"]=[UUID getUUID];