gpt4 book ai didi

ios - 检查特定用户名是否存在于 KeyChain 如果不存在则使用密码 ios objective-c 存储新用户

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:02:26 26 4
gpt4 key购买 nike

我需要将用户名和密码值存储到 keychain ,下次如果我想存储新的用户名和密码,如果用户名已经存在,它会显示消息,但如果用户名不同,它应该存储它。以下是我的代码我能够存储但不知道如何检查特定的用户名。

+(bool)CheckValuesInKeyChainWithUsername:(NSString*)username
{

NSDictionary* dictSearch = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword), kSecClass, kCFBooleanTrue, kSecReturnAttributes, kCFBooleanTrue, kSecReturnData, nil];
NSDictionary* found = nil;
CFDictionaryRef foundCF;
OSStatus errOS = SecItemCopyMatching((__bridge CFDictionaryRef) dictSearch, (CFTypeRef*)&foundCF);
NSLog(@"%d",(int)errOS);
found = (__bridge NSDictionary*)(foundCF);
if (!found)
{
return false;
}
return true;
}


+(void)SaveUsername:(NSString*)user withPassword:(NSString*)pass
{

// Create dictionary of parameters to add
NSData* passwordData = [pass dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword), kSecClass, passwordData, kSecValueData, user, kSecAttrAccount, nil];

// Try to save to keychain
OSStatus errOS = SecItemAdd((__bridge CFDictionaryRef) dict, NULL);
NSLog(@"Error Code: %d", (int)errOS);

}

最佳答案

这里是经过测试的代码。您需要将字典设置为可变的,还要检查您的情况是否存在无效参数 (errOS == errSecPara)。

    +(bool)CheckValuesInKeyChainWithUsername:(NSString*)username
{

NSMutableDictionary* dictSearch = [[NSMutableDictionary alloc]init];

[dictSearch setObject:(__bridge id)kSecClassGenericPassword
forKey:(__bridge id)kSecClass];

[dictSearch setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];

[dictSearch setObject:(__bridge id)kCFBooleanTrue
forKey:(__bridge id)kSecReturnAttributes];


[dictSearch setObject:username forKey:(__bridge id)kSecAttrAccount];

/*
Unique string used to identify the keychain item:
//static const UInt8 kKeychainItemIdentifier[] = "com.company.MyApp";


NSData *keychainItemID = [NSData dataWithBytes:kKeychainItemIdentifier
length:strlen((const char *)kKeychainItemIdentifier)];

[dictSearch setObject:keychainItemID forKey:(__bridge id)kSecAttrGeneric];
*/

NSMutableDictionary* found = nil;
CFMutableDictionaryRef foundCF = nil;
OSStatus errOS = noErr;
errOS = SecItemCopyMatching((__bridge CFDictionaryRef) dictSearch, (CFTypeRef*)&foundCF);
NSLog(@"%d",(int)errOS);


if (errOS == errSecItemNotFound)
{
return false;

}else if (errOS == noErr)
{
found = (__bridge NSMutableDictionary*)(foundCF);
return true;
}

return false;
}

关于ios - 检查特定用户名是否存在于 KeyChain 如果不存在则使用密码 ios objective-c 存储新用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41105272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com