jrendel / SwiftKeychainWrapper

A simple wrapper for the iOS Keychain to allow you to use it in a similar fashion to User Defaults. Written in Swift.
MIT License
1.59k stars 339 forks source link

KeyChain access between app and share extension #175

Closed fericit-bostan closed 2 years ago

fericit-bostan commented 2 years ago

I have an app and a share extension. I'm attempting to share data between the two via the KeyChain. I've added Keychain groups capability to both the app and extension using the group "com.co.MyMobileApp". I've also added App Groups capability to bother the app and extension as well using "group.com.co.MyMobileApp" as well and I have verified the abilities and identifiers on developer.apple.com for our app and share extension.

I've created a new instance of KeyChainWrapper and written the data using the following code in the App:

    let appIdentifierPrefix = "12345678XXX"
    let key = "currentUser.sharedData"
    let accessGroup = appIdentifierPrefix + ".com.co.MyMobileApp"
    let serviceName = Bundle.main.bundleIdentifier!
    let keyChain = KeychainWrapper.init(serviceName: serviceName, accessGroup: accessGroup) 
    keyChain.set(myKeyChainObject, forKey: key, withAccessibility: .afterFirstUnlock)

I'm attempting to read the data from the share extension using the following code:

    let appIdentifierPrefix = "12345678XXX"
    let key = "currentUser.sharedData"
    let accessGroup = appIdentifierPrefix + ".com.co.MyMobileApp"
    let serviceName = Bundle.main.bundleIdentifier!
    let keyChain = KeychainWrapper.init(serviceName: serviceName, accessGroup: accessGroup)
    let myKeyChainObject = keyChain.object(forKey: key)

But the object returned in the share extension is always nil. There is no error or warning so I am uncertain as to what I am doing wrong.

Thank you for the assistance.

fericit-bostan commented 2 years ago

I managed to resolve my issue. It seems that the cause of the problem was the usage of:

let serviceName = Bundle.main.bundleIdentifier!

This returns a different value for the share extension that that of the application. Once I hard coded this value I was able to access the persisted values in the KeyChain.