退出iOS上的应用后保持Firebase身份验证状态

问题描述 投票:0回答:2

我正在使用以下类来处理身份验证状态和用户登录:

class AuthenticationState: NSObject, ObservableObject {

     // MARK: Properties
    let db = Firestore.firestore()

    @Published var loggedInUser: FirebaseAuth.User?
    @Published var isAuthenticating = false
    @Published var error: NSError?

    static let shared = AuthenticationState()

    private let authState = Auth.auth()
    fileprivate var currentNonce: String?

    // MARK: Methods
    func login(with loginOption: LoginOption) {
        self.isAuthenticating = true
        self.error = nil

        switch loginOption {
            case .signInWithApple:
                handleSignInWithApple()

            case let .emailAndPassword(email, password):
                handleSignInWith(email: email, password: password)
        }
    }

    private func handleSignInWith(email: String, password: String) {
        authState.signIn(withEmail: email, password: password, completion: handleAuthResultCompletion)
    }

    func signup(email: String, password: String, passwordConfirmation: String) {
        guard password == passwordConfirmation else {
            self.error = NSError(domain: "", code: 9210, userInfo: [NSLocalizedDescriptionKey: "Password and confirmation does not match"])
            return
        }

        self.isAuthenticating = true
        self.error = nil

        authState.createUser(withEmail: email, password: password, completion: handleAuthResultCompletion)
    }

    private func handleAuthResultCompletion(auth: AuthDataResult?, error: Error?) {
        DispatchQueue.main.async {
        self.isAuthenticating = false
            if let user = auth?.user {
                self.loggedInUser = user
            } else if let error = error {
                self.error = error as NSError
            }
        }
    }

    func signout() {
        try? authState.signOut()
        self.loggedInUser = nil
    }
}

// Extension Below that handles sign in with apple, etc. 

这对于处理各种登录方法非常有用,但是当用户退出应用程序时,登录状态将不再保持。退出应用程序后让用户保持登录状态的最佳方法是什么?

ios swift firebase firebase-authentication
2个回答
0
投票

您可以通过多种方式来完成自己想做的事情。保存您的数据,任何类型的数据-取决于您自己的本地存储,例如:

  1. 默认
  2. 钥匙串
  3. 核心数据
  4. 还有其他。...

或者,我认为您可以尝试检查currentUser,如下所示:

let user = Auth.auth().currentUser

doc:https://firebase.google.com/docs/auth/ios/manage-users

并且对于javascript :(身份验证状态持久性)https://firebase.google.com/docs/auth/web/auth-state-persistence


0
投票

Firebase身份验证会自动将用户的身份验证状态保留在其钥匙串中,并在重新启动应用程序时尝试恢复该状态。

要恢复身份验证状态,需要使用服务器重新检查凭据,这可能需要一些时间。这就是为什么您需要使用auth状态监听器来选择此还原状态,如getting the currently signed in user上的文档所示:

handle = Auth.auth().addStateDidChangeListener { (auth, user) in
  // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.