【发布时间】:2020-09-18 08:03:43
【问题描述】:
我正在使用以下类来处理用户的身份验证状态和登录:
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