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 340 forks source link

iOS15 beta clearing keychain #171

Closed NickRussell95 closed 3 years ago

NickRussell95 commented 3 years ago

I am using this library to store an auth token on the users keychain. Everything works fine on iOS 14, however, it seems on the iOS 15 beta, the auth token gets deleted after a few hours causing the user to get logged out.

I am unsure if this is an issue with the library, or a bug in iOS 15.

NickRussell95 commented 3 years ago

This issue was caused by a race condition. I was trying to read from the keychain before the device had decrypted it - I'm not sure why it wasn't occurring in iOS14.

Solution:

    func refreshAuthFromKeychain(_ callback: @escaping (Bool) -> Void) {
        /// Avoid race condition where the app might try to access keychain data before the device has decrypted it
        guard UIApplication.shared.isProtectedDataAvailable else {
            NotificationCenter
                 .default
                 .publisher(for: UIApplication.protectedDataDidBecomeAvailableNotification)
                 .first()
                 .sink { _ in
                    self.refreshAuthFromKeychain(callback)
                  }.store(in: &cancellables)
            return
        }
     ....
    /// Then load from the keychain