Search code examples
ioskeychain

Keychain sharing between two apps


Apple has provided Generic Keychain sample which is written in Swift, I want to go ahead with Objective-C.

I have enabled keychain sharing in both the apps and on canOpenUrl I am able to invoke application B from A, now I want to share username and password from app A to app B. App ID is same for both the applications.

I have looked at various tutorials also don't want to use any third party project. Could not came to know how to pass the parameter from app A to app B.


Solution

  • Enable Keychain sharing:

    1. Turn on the Keychain Sharing capability.
    2. Select developer team
    3. Specify Keychain group name to something meaningful (for example testKeychainG1)
    4. Open .entitlements file and replace $(AppIdentifierPrefix) with your APP ID (for example AB123CDE45.testKeychainG1)

    Accessing Keychain (Retrieve shared items):

    let itemKey = "Item Key"
    
    let keychainAccessGroupName = "AB123CDE45.testKeychainG1"
    
    
    let query:[String:Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrAccount as String: itemKey,
        kSecReturnData as String: kCFBooleanTrue,
        kSecMatchLimit as String: kSecMatchLimitOne,
        kSecAttrAccessGroup as String: keychainAccessGroupName
    ]
    
    var result: AnyObject?
    
    let resultCodeLoad = withUnsafeMutablePointer(to: &result) {
        SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
    }
    
    if resultCodeLoad == noErr {
        if let result = result as? Data,
            let keyValue = NSString(data: result,
                                    encoding: String.Encoding.utf8.rawValue) as? String {
    
            // Found successfully
            print(keyValue)
        }
    } else {
        print("Error: \(resultCodeLoad)")
    }