Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift ';在展开可选值';时意外发现nil;,尽管每个财产都有价值_Swift_Firebase_Firebase Realtime Database - Fatal编程技术网

Swift ';在展开可选值';时意外发现nil;,尽管每个财产都有价值

Swift ';在展开可选值';时意外发现nil;,尽管每个财产都有价值,swift,firebase,firebase-realtime-database,Swift,Firebase,Firebase Realtime Database,我正在构建我的第一个Swift/iOS应用程序。我目前正在使用Firebase作为数据库 我一直面临一个令人沮丧的问题,在填写报名表后点击注册按钮时,我收到以下错误: fatal error: unexpectedly found nil while unwrapping an Optional value 当我看这个对象时,每个属性似乎都有它的价值。以下是我的Firebase注册功能: func handleRegister() { if let email = email

我正在构建我的第一个Swift/iOS应用程序。我目前正在使用Firebase作为数据库

我一直面临一个令人沮丧的问题,在填写报名表后点击注册按钮时,我收到以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value
当我看这个对象时,每个属性似乎都有它的价值。以下是我的Firebase注册功能:

 func handleRegister() {
        if let email = emailTextField.text, let password = passwordTextField.text, let fullName = fullNameTextField.text, let age = Int(ageTextField.text!), let username = userNameTextField.text {

            Auth.auth().createUser(withEmail: email, password: password ) { (user, error) in
                // ...

                if let firebaseError = error {
                    print(firebaseError.localizedDescription)
                    return
                }

                let userID = user!.uid

                //Instantiate our User model - set key values equal to optionals above from sign up form
                let userAccount = User(userId: userID, email: email, fullName: fullName, age: age, username: username)

                //Initialize an empty dictionary to hold the keys and values to upload to Firebase
                var userAccountDict = [String:AnyObject]()

                //Use a dictionary method to update the keys and matching values. The values are the ones from UserAccount model's properties and the keys are what we decide we want them to be named in FirebaseDatabase. Use these keys to extract the values
                userAccountDict.updateValue(userAccount.userId as AnyObject, forKey: "userId")
                userAccountDict.updateValue(userAccount.email as AnyObject, forKey: "email")
                userAccountDict.updateValue(userAccount.fullName as AnyObject, forKey: "fullName")
                userAccountDict.updateValue(userAccount.age as AnyObject, forKey: "age")
                userAccountDict.updateValue(userAccount.username as AnyObject, forKey: "username")


                //Upload dictionary with the keys and values set above. The database will hold these key/value pairs under the "users" node.
                self.ref.child("users").child(user!.uid).setValue(userAccountDict)
                print("User registered in Firebase with a userId of " + user!.uid)


            }
        }
    }
//    REGISTER BUTTON
    let registerButton: UIButton = {
        let button = UIButton(type: UIButtonType.system)
        button.isHidden = true
        button.isEnabled = false
        button.backgroundColor = UIColor.red
        button.setTitle("Register", for: UIControlState.normal)
        button.setTitleColor(.white, for: UIControlState.normal)
        button.titleLabel?.font = UIFont(name: "Futura", size: 16)
        button.layer.cornerRadius = 5
        button.clipsToBounds = true
        button.translatesAutoresizingMaskIntoConstraints = false

        button.addTarget(self, action: #selector(handleRegister), for: .touchUpInside)
        button.addTarget(self, action: #selector(toAppFeed), for: UIControlEvents.touchUpInside)


        return button
    }()
注册过程目前是以编程方式完成的,而不是故事板。下面是我最终调用HandlerRegister()函数的按钮:

 func handleRegister() {
        if let email = emailTextField.text, let password = passwordTextField.text, let fullName = fullNameTextField.text, let age = Int(ageTextField.text!), let username = userNameTextField.text {

            Auth.auth().createUser(withEmail: email, password: password ) { (user, error) in
                // ...

                if let firebaseError = error {
                    print(firebaseError.localizedDescription)
                    return
                }

                let userID = user!.uid

                //Instantiate our User model - set key values equal to optionals above from sign up form
                let userAccount = User(userId: userID, email: email, fullName: fullName, age: age, username: username)

                //Initialize an empty dictionary to hold the keys and values to upload to Firebase
                var userAccountDict = [String:AnyObject]()

                //Use a dictionary method to update the keys and matching values. The values are the ones from UserAccount model's properties and the keys are what we decide we want them to be named in FirebaseDatabase. Use these keys to extract the values
                userAccountDict.updateValue(userAccount.userId as AnyObject, forKey: "userId")
                userAccountDict.updateValue(userAccount.email as AnyObject, forKey: "email")
                userAccountDict.updateValue(userAccount.fullName as AnyObject, forKey: "fullName")
                userAccountDict.updateValue(userAccount.age as AnyObject, forKey: "age")
                userAccountDict.updateValue(userAccount.username as AnyObject, forKey: "username")


                //Upload dictionary with the keys and values set above. The database will hold these key/value pairs under the "users" node.
                self.ref.child("users").child(user!.uid).setValue(userAccountDict)
                print("User registered in Firebase with a userId of " + user!.uid)


            }
        }
    }
//    REGISTER BUTTON
    let registerButton: UIButton = {
        let button = UIButton(type: UIButtonType.system)
        button.isHidden = true
        button.isEnabled = false
        button.backgroundColor = UIColor.red
        button.setTitle("Register", for: UIControlState.normal)
        button.setTitleColor(.white, for: UIControlState.normal)
        button.titleLabel?.font = UIFont(name: "Futura", size: 16)
        button.layer.cornerRadius = 5
        button.clipsToBounds = true
        button.translatesAutoresizingMaskIntoConstraints = false

        button.addTarget(self, action: #selector(handleRegister), for: .touchUpInside)
        button.addTarget(self, action: #selector(toAppFeed), for: UIControlEvents.touchUpInside)


        return button
    }()
以下是我在控制台旁边的左窗格中看到的内容:

我看到的唯一一件事是错误,我想应该是零,因为Firebase没有抛出任何错误。即使如此,它也不在我发布到Firebase的对象中。我应该提到,当我检查Firebase时,我会看到我创建的每个用户,但是我从HandlerRegister()函数收集的所有用户数据都不会保存到数据库中

我已经在Firebase工作了几个月,以前从未遇到过这个问题。我已经研究了其他的SO问题,但似乎没有一个能解决这个具体问题。此时我能想到的唯一一件事是,调用handleRegister()时,某些内容仍然为零,然后获得一个值。但我不确定

非常感谢在这方面的任何帮助

编辑-填写表单后按下“注册”按钮后显示错误:

您试图在字典中使用键引用来分配值,但是这些键还不可用,这就是问题所在相信我

这是解决办法 var userAccountDict=[String:Any]()

userAccountDict[“userId”]=userAccount.userId 等等


祝你好运:)

有些东西确实被强行拆开了,但这不是我的变数

Firebase参考最初设置为

ref: DatabaseReference!
在self.ref.child中,ref需要一个?:

self.ref?.child
当然,控制台并没有很好地揭示这一点。所以ref被强制展开,当我在handleRegister()函数中使用它时,我没有检查它是否存在


我还忘了在viewDidLoad()中实例化我的Firebase引用。错误发生在哪一行?您应该使用Swift字典语法:
userAccountDict[“userId”]=userAccount.userId
,而不是
userAccountDict.updateValue(userAccount.userId作为AnyObject,forKey:“userId”)
,虽然我不认为这是导致CrashHandlerRegister崩溃的原因,但它是一种异步方法,您应该使用完成句柄Hey@Connor,谢谢您的消息。它发生在我的self.ref.child线路上。我将添加上面错误的图像。这就是造成崩溃的原因,我确实提到密钥不可用,他正在尝试更新该密钥的值。但这会很奇怪,因为我以前在创建新用户时在其他测试项目中使用过此方法,并且它是有效的。不过我还是要试一试。谢谢