iOS keychain sharing 詳細步驟

要在兩個app間共享keychain。以下是步驟:

1:添加Security.framework,詳細步驟如下圖


添加Security.framework

2:打開Keychain Sharing。 在xcode中,點擊項目TARGETS->Capabilities下拉找到Keychain Sharing選項,然后打開,xcode會自動添加一個項目,如下圖,

說明一下:打開按鈕的時候,xcode會自動添加上當前app的一個group值,這個groupName就是要keychain要保存時候用到的groupName,可以有多個groupName;


打開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];

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容