无法获取默认 Firebase 数据库实例。必须调用`[FIRApp配置]

bad*_*icy 4 firebase swift firebase-realtime-database

当我尝试向 Firebase 验证用户时,没问题,但是当我尝试写入数据库用户的电子邮件地址时,出现错误。

我的代码:

import UIKit
import Firebase

class ViewController: UIViewController {

    @IBOutlet weak var emailField: UITextField!
    @IBOutlet weak var sifreField: UITextField!
    @IBOutlet weak var sifre1Field: UITextField!

    var ref = Database.database().reference()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func kayitBtn(_ sender: Any)
    {
        if(sifreField.text != sifre1Field.text)
        {
            print("****error****")
        }
        else if ( !(emailField.text?.isEmpty)! || !(sifreField.text?.isEmpty)! || !(sifre1Field.text?.isEmpty)! )
        {
            Auth.auth().createUser(withEmail: emailField.text!, password: sifreField.text!) { (user, error) in
                if error != nil
                {
                    print ("***error***")
                }
                else if ( !(self.emailField.text?.isEmpty)! || !(self.sifreField.text?.isEmpty)!  || !(self.sifre1Field.text?.isEmpty)! )
                {
                    self.ref.child("users").child((user?.uid)!).setValue(["email": self.emailField.text!])
                    print("database ok")
                }
        }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

我的 AppDelegate.swift(在 中添加import Firebase和 FirebaseApp.configure() didFinishLaunchingWithOptions):

import UIKit
import CoreData
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()
        return true
    }
Run Code Online (Sandbox Code Playgroud)

我的控制台错误:

在此处输入图片说明

我现在该怎么办?谢谢你的一切。

小智 5

var ref: FIRDatabaseReference!

override func viewDidLoad() {
    super.viewDidLoad()
    ref = FIRDatabase.database().reference()
}
Run Code Online (Sandbox Code Playgroud)

这将解决您的问题,并且应用程序不会崩溃。