IOS developer based in barcelona.

Share Keychain Between App and Extension

Last week, I was using Firebase Authentication, when a user is logged you can access to the current user with the next line of code:

let user = Auth.auth().currentUser

I was trying to solve a problem, whether I open an app extension (for instance a Share Extension), I was unable to retrieve the current user. The current user was only available on the main app target. After searching the best solution, I found a “good“ approach to follow, storing the current user into the keychain and then get it from my app extension.

First of all, go to your app target, in Capabilities. You must turn on the App Groups

Screen Shot 2019-01-02 at 22.48.26.png

then, you need to turn on the Keychain Sharing

Screen Shot 2019-01-02 at 22.52.00.png

When you have turned on the above Capabilities, you need your prefix, you will use it later (you can get it from the apple member center, app identifiers section)

Screen Shot 2019-01-02 at 22.54.30.png

With these information, you can share info between your main app and app extension.

You’ll need the access group name, and the prefix joined with the bundler identifier

The code below shows how:

import Foundation
import Firebase
import KeychainAccess

protocol Keychainable {
    func save(user: User)
    func get() -> User

struct KeychainUser: Keychainable {
    let keychain = Keychain(service: "", accessGroup: "group.albertomoral.readit")
    func save(user: User) {
        let userData = try! NSKeyedArchiver.archivedData(withRootObject: user, requiringSecureCoding: false)
        try! keychain.set(userData, key: "firebase_user")
    func get() -> User {
        let value = try! keychain.getData("firebase_user")
        return try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(value!) as! User

I’ve used a Pod in order to work with Keychain

Strong typed Ids in Swift