那些年保存设备识别码keychainitemwrapper使用中
2017-02-24 本文已影响1549人
一只知更鸟的人生
突然间想到设备唯一识别码的事情,然后想研究一下,然后就在网上搜了许多资料,讲'keychainitemwrapper'的资料挺多的,但都大同小异,于是乎我选择了一篇文章按照方法来做,但是一直报错,按照这位仁兄的《iOS获取设备唯一标识码》文章一步步下来,结果报了下面的错误:
- (void)saveUuidWithKeyChain:(NSString *)uuid
{
NSString *strUUID = [self.keychainItem objectForKey:(id)kSecValueData];
if (strUUID == nil || strUUID.count==0)
{
[self.keychainItem setObject:uuid forKey:(id)kSecValueData];
}
}
QQ20170224-1@2x.png
后来打印了值,才发现原来取出来的数据不是
NSString
,而是NSArray
:QQ20170224-0@2x.png
代码修改后
- (void)saveUuidWithKeyChain:(NSString *)uuid
{
NSArray *strUUID = [self.keychainItem objectForKey:(id)kSecValueData]; // 此处不是NSString
if (strUUID == nil || strUUID.count==0)
{
[self.keychainItem setObject:@[uuid] forKey:(id)kSecValueData]; // 存入的是数组类型
}
}
问题解决了。
另外我有个问题一直没明白,一旦我初始化指定accessGroup
参数,就会出错,设置为nil反而好了,请大神指教。
self.keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"UUID" accessGroup:@"com.hp.uuidDemo"];
2017-02-24 11:55:39.010 UUIDDemo[685:210914] 21AF6998-21B2-4711-94B2-DA37EB4CDD48
2017-02-24 11:55:39.021 UUIDDemo[685:210914] *** Assertion failure in -[KeychainItemWrapper writeToKeychain], /Users/hp/workspaces/TYHS/UUIDDemo/UUIDDemo/KeychainItemWrapper.m:363
(lldb)
以下是demo内容:
// 引入头文件
#import "ViewController.h"
#import <Security/Security.h>
#import "KeychainItemWrapper.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *UUIDTextField;
/** uuid*/
@property (assign, nonatomic) long uuid;
/** KeychainItemWrapper*/
@property (strong, nonatomic) KeychainItemWrapper *keychainItem;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化
self.keychainItem = [[KeychainItemWrapper alloc]
initWithIdentifier:@"UUID" accessGroup:@"com.hp.uuidDemo"];
}
// 生成UUID
- (NSString *)getUUID{
CFUUIDRef uuid = CFUUIDCreate(nil);
CFStringRef uuidString = CFUUIDCreateString(nil, uuid);
NSString *result = CFBridgingRelease(CFStringCreateCopy(NULL, uuidString));
CFRelease(uuid);
CFRelease(uuidString);
return result;
}
- (IBAction)saveUUID:(UIButton *)sender {
[self.keychainItem resetKeychainItem];
NSString *uuid = [self getUUID];
self.UUIDTextField.text = uuid;
NSLog(@"%@", uuid);
[self saveUuidWithKeyChain:uuid];
// 0C3776B9-F6FA-430A-84F1-BC446B83A275
//
}
- (IBAction)readUUID:(UIButton *)sender {
self.UUIDTextField.text = [self getKeychain];
NSLog(@"%@", self.UUIDTextField.text);
}
// 保存UUID
- (void)saveUuidWithKeyChain:(NSString *)uuid
{
NSArray *strUUID = [self.keychainItem objectForKey:(id)kSecValueData];
if (strUUID == nil || strUUID.count==0)
{
[self.keychainItem setObject:@[uuid] forKey:(id)kSecValueData];
}
}
// 获取保存在keychain中的UUID
- (NSString *)getKeychain {
NSArray *strUUIDDArray = [self.keychainItem objectForKey:(id)kSecValueData];
NSString *strUUID = strUUIDDArray.firstObject;
return strUUID;
}
@end