要运行示例项目,首先克隆仓库,然后从 Example 目录运行 pod install
实际上它还没有通过 CocoaPods 提供,因此在此期间使用
pod 'XKKeychain', :git => 'https://github.com/karlvr/XKKeychain.git'
#import <XKKeychain/XKKeychain.h>
最常用的密钥链项类型是通用密码项类型。要访问它,我们使用 XKKeychainGenericPasswordItem
类。每个密钥链项都由其类型、服务名称和帐户唯一标识。服务名称和帐户是任意字符串。服务名称通常标识服务,如您的应用或第三方服务。帐户名称通常标识存储凭证的该服务上的帐户。
密钥链项包含一个 secret
。这是您存储受保护信息的地方。XKKeychain 提供通过 NSData
、NSString
、NSDictionary
或 id<NSCoding>
访问密钥的方法。您还可以简单地使用 objectForKey:
或密钥索引在地面上。只是确保使用与您存储密钥时相同的方法检索密钥,因为地下密钥是 NSData
。
NSString * const serviceName = @"your app name, or the service you're accessing, e.g. com.twitter";
NSString * const accountName = @"the account name the credential is for, e.g. avon";
XKKeychainGenericPasswordItem *item = [XKKeychainGenericPasswordItem itemForService:serviceName account:accountName error:&error];
if (error) {
NSLog(@"Failed to access the keychain: %@", [error localizedDescription]);
}
NSString *secretString = item.secret.stringValue;
您可以以不同类型访问密钥。您应以您放入的类型访问它。
NSData *secretData = item.secret.dataValue;
NSDictionary *secretDictionary = item.secret.dictionaryValue;
id secretValue = item.secret[@"aKey"];
id secret = item.secret.transformableValue; /* Using NSCoding */
您可以在密钥链项中存储附加信息。此信息不是机密的。它位于 generic
属性中,该属性支持与密钥相同的不同值类型。
NSString *myString = item.generic.stringValue;
NSData *myData = item.generic.dataValue;
NSDictionary *myDictionary = item.generic.dictionaryValue;
id myValue = item.generic[@"aKey"];
id myObject = item.generic.transformableValue; /* Using NSCoding */
您可以从密钥链检索项的数组。
NSError *error = nil;
NSArray *items = [XKKeychainGenericPasswordItem itemsForService:serviceName error:&error];
XKKeychainGenericPasswordItem *item = [XKKeychainGenericPasswordItem new];
item.service = serviceName;
item.account = accountName;
item.accessible = kSecAttrAccessibleAfterFirstUnlock;
item.secret.stringValue = @"top secret";
item.generic[@"aKey"] = @"a non private value";
NSError *error = nil;
if (![item saveWithError:&error]) {
NSLog(@"Failed to save to the keychain: %@", [error localizedDescription]);
}
Karl von Randow, [email protected]
XKKeychain遵循MIT许可证。更多信息请参阅LICENSE文件。