iOS Swift实现用户自动登录及Firestore用户校验方案咨询
Hey there! Let's tackle your two core requirements: keeping users logged in automatically (until they actively sign out) and verifying if a user already exists in Cloud Firestore. Here's how to implement both with your existing code:
1. Implement Automatic Persistent Login
Firebase Auth handles session persistence by default, but we need to explicitly check for an existing user when the app launches to skip the login flow. Here's the breakdown:
Step 1: Confirm Persistence Setting
First, make sure Firebase Auth is set to store sessions locally (this is the default, but it's good to confirm). Add this to your app's initialization code (like AppDelegate or SceneDelegate):
// In application(_:didFinishLaunchingWithOptions:) Auth.auth().setPersistence(.local) { error in if let error = error { print("Persistence setup error: \(error.localizedDescription)") } }
.local ensures the session stays saved across app restarts and device reboots.
Step 2: Check for Existing User on App Launch
Add this check to your login view controller's viewDidLoad() to bypass the login screen if the user is already signed in:
override func viewDidLoad() { super.viewDidLoad() // Skip login if user has an active session if let currentUser = Auth.auth().currentUser { print("User is already logged in: \(currentUser.uid)") // Redirect to the appropriate screen if PrefsManager.sharedinstance.isFirstTime == false { performSegue(withIdentifier: "signUpToTabBar", sender: nil) } else { let storyboard = UIStoryboard(name: "Start", bundle: nil) let initialViewController = storyboard.instantiateViewController(withIdentifier: "onboardvc") present(initialViewController, animated: true, completion: nil) } } }
Step 3: Handle Manual Logout
Add this function wherever you want to let users sign out (e.g., a settings screen):
func signOutUser() { do { try Auth.auth().signOut() // Redirect back to login screen let storyboard = UIStoryboard(name: "YourLoginStoryboardName", bundle: nil) let loginVC = storyboard.instantiateInitialViewController() UIApplication.shared.windows.first?.rootViewController = loginVC } catch let signOutError as NSError { print("Sign out error: \(signOutError.localizedDescription)") } }
2. Check if a User Exists in Cloud Firestore
Right now your code overwrites the user's document on every login. Instead, we'll first check if the user's UID exists in the users collection to distinguish between new and returning users. Here's how to update your loginusingOTP function:
func loginusingOTP(OTPtext: String) { let db = Firestore.firestore() let verificationID = self.Userdefaults.string(forKey: "authVerificationID") let credential: PhoneAuthCredential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID!, verificationCode: OTPtext) Auth.auth().signIn(with: credential) { (user, error) in if error != nil { print("error: \(String(describing: error?.localizedDescription))") } else if let currentUser = user { print("Phone number: \(String(describing: currentUser.phoneNumber))") let userUID = currentUser.uid // Check if user exists in Firestore db.collection("users").document(userUID).getDocument { (document, error) in if let error = error { print("Error checking user existence: \(error)") return } if let document = document, document.exists { // Returning user - go straight to home print("Existing user found") PrefsManager.sharedinstance.isFirstTime = false self.performSegue(withIdentifier: "signUpToTabBar", sender: nil) } else { // New user - send to details page to fill info print("New user detected") PrefsManager.sharedinstance.isFirstTime = true let storyboard = UIStoryboard(name: "Start", bundle: nil) let initialViewController = storyboard.instantiateViewController(withIdentifier: "onboardvc") self.present(initialViewController, animated: true, completion: nil) // After user submits details in onboardvc, save to Firestore: // db.collection("users").document(userUID).setData([ // "User_Phone_number": currentUser.phoneNumber as Any, // "uid": userUID, // // Add other fields like name, email here // ]) } } } else { print("error::::::") } } }
Key Notes:
- We use
getDocument()on the user's UID-specific document for fast, efficient existence checks (document lookups are optimized in Firestore). - For new users, redirect to your details page first, then save their full profile to Firestore once they submit the form.
- Update the
isFirstTimepreference based on the Firestore check instead of relying on a pre-set value.
内容的提问来源于stack exchange,提问作者PvDev

