要在兩個app間共享keychain夷磕。以下是步驟:
1:添加Security.framework,詳細(xì)步驟如下圖
2:打開Keychain Sharing仔沿。 在xcode中坐桩,點擊項目TARGETS->Capabilities下拉找到Keychain Sharing選項,然后打開封锉,xcode會自動添加一個項目绵跷,如下圖,
說明一下:打開按鈕的時候成福,xcode會自動添加上當(dāng)前app的一個group值碾局,這個groupName就是要keychain要保存時候用到的groupName,可以有多個groupName;
3:然后就是寫代碼了奴艾。我用的是UICKeyChainStore庫净当,
下載地址在這里: https://github.com/kishikawakatsumi/UICKeyChainStore
保存的地方,#import "UICKeyChainStore.h"
然后蕴潦,下面是一些工具函數(shù)
/*
@description生成通用的keychain ServiceName
@return str生成后的服務(wù)名
*/
+ (NSString*)keychainServiceName {
NSString*identifier = [[NSBundlemainBundle]bundleIdentifier];
returnidentifier;
}
/*
@description生成統(tǒng)一的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;
}
上面的函數(shù)像啼,用戶生成通用的的groupName ,serviceName,這些都是在初始化keyChain對象的時候用到的潭苞。
注意忽冻,其中生成groupName的函數(shù),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];