You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xcode8(Swift3)集成FirebaseAuth创建Register类遇问题求助

Fixing Firebase Registration for Xcode 8 (Swift 3)

Hey there! Let's get your Firebase registration working smoothly in Xcode 8 with Swift 3. The core issue here is that the tutorial you're following uses the old Firebase 2.x SDK API, but Firebase has since rolled out a fully updated SDK (v3+) with rewritten methods that aren't compatible with the older code. On top of that, Swift 3 introduced syntax changes that break Swift 2-era code.

Key Issues in Your Current Code

  • Firebase 3+ no longer uses BASE_REF.createUser() or BASE_REF.authUser() — authentication is now handled via FIRAuth.auth()
  • Swift 3 updated method names (e.g., performSegueWithIdentifier → performSegue(withIdentifier:), presentViewController → present(_:animated:completion:))
  • Variable mismatches (you reference password but your variable is named pass, plus result ["uid"] has an extra space)
  • NSUserDefaults syntax changed in Swift 3
  • Firebase 3+ returns a FIRUser object instead of the old authData type

Updated Working Code

import Foundation
import FirebaseAuth
import Toast_Swift

class Register: UIViewController {
    @IBOutlet weak var emailField: UITextField!
    @IBOutlet weak var passField: UITextField!
    
    @IBAction func registerButton(_ sender: Any) {
        guard let email = emailField.text, !email.isEmpty,
              let pass = passField.text, !pass.isEmpty else {
            signupErrorAlert(title: "Ups!", message: "Zaboravili ste da popunite e-mail i/ili sifra polje.")
            return
        }
        
        // Firebase 3+ create user method (auto-logs user in after success)
        FIRAuth.auth()?.createUser(withEmail: email, password: pass) { [weak self] authResult, error in
            guard let self = self else { return }
            
            if let error = error {
                // Handle registration failure
                self.signupErrorAlert(title: "Ups!", message: "Nastao je problem pri kreiranju naloga. Probajte ponovo.")
                print("Registration error details: \(error.localizedDescription)")
                return
            }
            
            // Confirm we have a valid user object
            guard let user = authResult?.user else { return }
            
            // Store user UID in UserDefaults for future access
            UserDefaults.standard.set(user.uid, forKey: "uid")
            
            // Prepare user data for your DataService
            let userData = ["provider": user.providerID, "email": email]
            
            // Call your custom DataService to finalize account setup
            DataService.dataService.createNewAccount(user.uid, user: userData)
            
            // Navigate to the main app flow
            self.performSegue(withIdentifier: "NewUserLoggedIn", sender: nil)
        }
    }
    
    func signupErrorAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }
}

Important Changes Explained

  • Firebase Auth Update: We now use FIRAuth.auth()?.createUser(withEmail:password:completion:) — this method automatically signs in the user after successful registration, so you don't need a separate authUser call anymore.
  • Safer Optional Handling: Used guard let to safely unwrap text field values and avoid force-unwrapping risks.
  • Swift 3 Syntax Compliance: Updated all method names to match Swift 3 conventions and replaced NSUserDefaults with the modern UserDefaults API.
  • Memory Safety: Added [weak self] in the completion block to prevent retain cycles (a common source of memory leaks in iOS apps).
  • Clearer Error Logging: Added a print statement for error details to help debug issues if they pop up later.

内容的提问来源于stack exchange,提问作者Martin Pošmuga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:45:26