Swift 4+Firebase注册:ViewController间Email值传递及注册实现
Two-Step Signup with Swift 4 & Firebase: Passing Data Between View Controllers
Hey there! Let's walk through implementing this two-step signup flow—first collecting the email, then the password, and finally submitting both to Firebase Authentication. Here's how to make it work smoothly:
Step 1: Pass Email from First View Controller to Second
The simplest way to pass the email is by adding a public property to your second view controller, then setting that property when you navigate from the first VC.
First View Controller Code
Assume you have a UITextField for email input and a "Next" button. We'll add validation for the email format before navigating:
// FirstViewController.swift import UIKit class FirstViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBAction func nextButtonTapped(_ sender: UIButton) { // Validate email input guard let userEmail = emailTextField.text, !userEmail.isEmpty, isValidEmail(userEmail) else { showAlert(title: "Invalid Email", message: "Please enter a valid email address.") return } // Navigate to Second VC and pass the email guard let secondVC = storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else { fatalError("Couldn't instantiate SecondViewController") } secondVC.userEmail = userEmail navigationController?.pushViewController(secondVC, animated: true) } // Helper: Email format validation private func isValidEmail(_ email: String) -> Bool { let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email) } // Helper: Reusable alert method private func showAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) present(alert, animated: true) } }
Second View Controller Setup
Add a property to store the incoming email, then set up your password field and signup button:
// SecondViewController.swift import UIKit import FirebaseAuth class SecondViewController: UIViewController { @IBOutlet weak var passwordTextField: UITextField! // This property will hold the email from FirstVC var userEmail: String! @IBAction func signupButtonTapped(_ sender: UIButton) { // Validate password input (Firebase requires min 6 chars) guard let userPassword = passwordTextField.text, !userPassword.isEmpty, userPassword.count >= 6 else { showAlert(title: "Invalid Password", message: "Password must be at least 6 characters long.") return } // Submit email & password to Firebase Auth Auth.auth().createUser(withEmail: userEmail, password: userPassword) { [weak self] authResult, error in guard let self = self else { return } if let error = error { // Handle signup errors (e.g., email already exists, weak password) self.showAlert(title: "Signup Failed", message: error.localizedDescription) return } // Signup successful! Redirect to home or show success self.showAlert(title: "Success!", message: "Your account is created.") { // Replace with your home VC navigation logic let homeVC = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") self.navigationController?.setViewControllers([homeVC!], animated: true) } } } // Reusable alert with optional completion private func showAlert(title: String, message: String, completion: (() -> Void)? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completion?() }) present(alert, animated: true) } }
Important Notes
- Storyboard Setup: Make sure your second view controller has a storyboard identifier (e.g., "SecondViewController") set in the Identity Inspector.
- Firebase Configuration: Ensure you've added the
GoogleService-Info.plistto your project and importedFirebaseAuthin the second VC. - Error Handling: Firebase's
createUsermethod returns detailed errors—we're usingerror.localizedDescriptionto show user-friendly messages. - Memory Safety: We use
[weak self]in the Firebase closure to avoid retain cycles.
内容的提问来源于stack exchange,提问作者ozy
相关产品推荐
相关产品推荐

