IOS获取唯一设备ID(钥匙串存储)
2016-09-03 本文已影响235人
蜗牛1992
+ (NSString *)getDeviceId
{
NSString * currentDeviceUUIDStr = [ApplicationUtil chainLoad];
if (currentDeviceUUIDStr == nil || [currentDeviceUUIDStr isEqualToString:@""])
{
NSUUID * currentDeviceUUID = [UIDevice currentDevice].identifierForVendor;
currentDeviceUUIDStr = currentDeviceUUID.UUIDString;
currentDeviceUUIDStr = [currentDeviceUUIDStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
currentDeviceUUIDStr = [currentDeviceUUIDStr lowercaseString];
[ApplicationUtil chainSave:currentDeviceUUIDStr];
}
return currentDeviceUUIDStr;
}
导包Security.framework,导头文件#import <Security/Security.h>
//钥匙串操作
+ (void)chainSave:(NSString *)service;
+ (NSString *)chainLoad;
+ (void)chainDelete:(NSString *)service;
//钥匙串操作
+ (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);
}
+ (void)chainSave:(NSString *)service {
NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
[tempDic setObject:service forKey:kDictionaryKey];
[self save:kKeyChainKey data:tempDic];
}
//取
+ (NSString *)chainLoad{
NSMutableDictionary *tempDic = (NSMutableDictionary *)[self load:kKeyChainKey];
return [tempDic objectForKey:kDictionaryKey];
}
+ (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:(__bridge NSData *)keyData];
} @catch (NSException *e) {
NSLog(@"Unarchive of %@ failed: %@", service, e);
} @finally {
}
}
if (keyData)
CFRelease(keyData);
return ret;
}
//删
+ (void)chainDelete{
[self delete:kKeyChainKey];
}
+ (void)delete:(NSString *)service {
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
SecItemDelete((CFDictionaryRef)keychainQuery);
}