在iOS上退出应用程序后保持Firebase身份验证状态
我使用以下类来处理用户的身份验证状态和登录:在iOS上退出应用程序后保持Firebase身份验证状态,ios,swift,firebase,firebase-authentication,Ios,Swift,Firebase,Firebase Authentication,我使用以下类来处理用户的身份验证状态和登录: class AuthenticationState: NSObject, ObservableObject { // MARK: Properties let db = Firestore.firestore() @Published var loggedInUser: FirebaseAuth.User? @Published var isAuthenticating = false @Publishe
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.
这非常适合处理各种登录方法,但是当用户退出应用程序时,登录状态不再持续。退出应用程序后,让用户保持登录状态的最佳方式是什么?您可以通过多种方式完成自己想做的事情。保存您的数据,任何类型的数据—由您在本地存储中决定,例如:
currentUser
,如下所示:
let user = Auth.auth().currentUser
文件:
对于javascript:(身份验证状态持久化)
)Firebase身份验证自动将用户的身份验证状态保留到其密钥链,并在应用程序重新启动时尝试恢复该状态 要恢复身份验证状态,它需要与服务器重新检查凭据,这可能需要一些时间。这就是为什么需要使用身份验证状态侦听器来获取此还原状态,如以下文档所示:
好的,我知道我需要添加一个侦听器,我只是不太确定在哪里实现它。我是否将其作为方法包含在AuthenticationState类中?检查
Auth.Auth()。我添加了一个函数,将我的登录用户设置为Auth.Auth()。如果保存了一个,则currentUser
,否则默认为登录屏幕。非常感谢。
handle = Auth.auth().addStateDidChangeListener { (auth, user) in
// ...
}