iOS keychain sharing 详细步骤

要在两个app间共享keychain。以下是步骤:

1:添加Security.framework,详细步骤如下图


iOS keychain sharing 详细步骤_第1张图片
添加Security.framework

2:打开Keychain Sharing。 在xcode中,点击项目TARGETS->Capabilities下拉找到Keychain Sharing选项,然后打开,xcode会自动添加一个项目,如下图,

说明一下:打开按钮的时候,xcode会自动添加上当前app的一个group值,这个groupName就是要keychain要保存时候用到的groupName,可以有多个groupName;


iOS keychain sharing 详细步骤_第2张图片
打开KeyChain Sharing

3:然后就是写代码了。我用的是UICKeyChainStore库,

下载地址在这里: https://github.com/kishikawakatsumi/UICKeyChainStore

保存的地方,#import "UICKeyChainStore.h"

然后,下面是一些工具函数

/*

@description生成通用的keychain ServiceName

@return str生成后的服务名

*/

+ (NSString*)keychainServiceName {

NSString*identifier = [[NSBundlemainBundle]bundleIdentifier];

returnidentifier;

}

/*

@description生成统一的keychain组名

@return str生成后的组名

*/

+ (NSString*)keychainGroupName {

NSString*bundleSeedID = [selfbundleSeedID];

NSString*groupName = [bundleSeedIDstringByAppendingString:@"."];

groupName = [groupNamestringByAppendingString:[selfkeychainServiceName]];

returngroupName;

}


/*

@description:获取bundleSeedID

@return获取到的bundleSeedID

*/

+ (NSString*)bundleSeedID {

NSDictionary*query = [NSDictionarydictionaryWithObjectsAndKeys:

kSecClassGenericPassword,kSecClass,

@"bundleSeedID",kSecAttrAccount,

@"",kSecAttrService,

(id)kCFBooleanTrue,kSecReturnAttributes,

nil];

CFDictionaryRefresult =nil;

OSStatusstatus =SecItemCopyMatching((CFDictionaryRef)query, (CFTypeRef*)&result);

if(status ==errSecItemNotFound)

status =SecItemAdd((CFDictionaryRef)query, (CFTypeRef*)&result);

if(status !=errSecSuccess)

returnnil;

NSString*accessGroup = [(__bridgeNSDictionary*)resultobjectForKey:kSecAttrAccessGroup];

NSArray*components = [accessGroupcomponentsSeparatedByString:@"."];

NSString*bundleSeedID = [[componentsobjectEnumerator]nextObject];

CFRelease(result);

returnbundleSeedID;

}

上面的函数,用户生成通用的的groupName ,serviceName,这些都是在初始化keyChain对象的时候用到的。

注意,其中生成groupName的函数,groupName的格式必须是bundleSeed后面接".",再接上面步骤2中,keychain sharing列表生成的某一个groupName。

然后在随便起一个key 

#define groupKey @"lallalallalal"

保存的代码:

UICKeyChainStore*keychain = [UICKeyChainStorekeyChainStoreWithService:[selfkeychainServiceName]accessGroup:[selfkeychainGroupName]];

[keychain setString:stringToSave forKey:groupKey];

提取代码

UICKeyChainStore*keychain = [UICKeyChainStorekeyChainStoreWithService:[selfkeychainServiceName]accessGroup:[selfkeychainGroupName]];

NSString *stringSaved = [keychain stringForKey:groupKey];

删除代码:

UICKeyChainStore*keychain = [UICKeyChainStorekeyChainStoreWithService:[selfkeychainServiceName]accessGroup:[selfkeychainGroupName]];

[keychainremoveItemForKey:groupKey];

你可能感兴趣的:(iOS keychain sharing 详细步骤)