无法从Firebase读取。返回空

时间:2018-08-12 06:57:20

标签: swift firebase firebase-realtime-database

我想读取用户名,并将其写回Firebase中的另一个孩子中。但它返回空:

private var nameFromFirebase: String = ""    

我正在尝试这样阅读:

 override func viewDidLoad() {
        super.viewDidLoad()

        ref = Database.database().reference()

        //Get userinfo from database
        let user = Auth.auth().currentUser!.uid
        ref?.child("users").child(user).observeSingleEvent(of: .value, with: { (snapshot) in

            guard let userDict = snapshot.value as? [String: Any],
                let name = userDict["Name"] as? String {
                    return
            }

            //Declare variables for use
            self. nameFromFirebase = name

        })

    }    

@IBAction func sendInfoButton(_ sender: UIButton) {
      let data = ["Name" : nameFromFirebase] as [String : Any]
                self.ref?.child("Info").child(dateAndTime).updateChildValues(data, withCompletionBlock: { (error, ref) in
                    if error != nil{
                        print(error!)
                        return
                    }

                })    
}    

这只会在Firebase中写入“”。我想念什么?

编辑*
我正在为此写信给Firebase:

@IBAction func registerButton(_ sender: UIButton) {

            Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: { (User: User?, error: Error!) in
                if error != nil {
                    if let errCode = AuthErrorCode(rawValue: error!._code) {

                        switch errCode {
                        case .invalidEmail:
                            self.errorMsg(title: "Error", message: "E-mail format is wrong")
                        case .emailAlreadyInUse:
                            self.errorMsg(title: "Error", message: "E-mail already in use")
                        case .weakPassword:
                            self.errorMsg(title: "Error", message: "Password must contain at least 6 characters")
                        default:
                            print("Create User Error: \(error!)")
                        }
                    }


                    return
                }
                //Register userinfo in Firebase
                let ref = Database.database().reference()
                let usersRefrence = ref.child("users")
                let uid = User?.uid
                let newUserRefrence = usersRefrence.child(uid!)
                newUserRefrence.setValue(["Name": self.nameTextField.text!, "Address": self.addressTextField.text!, "Phone": self.phoneTextField.text!])
            })

        }    

Firebasestructure:

{
  "Info" : {
    "13-8-2018 at: 7:38:21" : {
      "Name" : ""
    }
  },
  "users" : {
    "6VzpfP9qxBUVSZtdYSbyHe9MfVv2" : {
      "Address" : "Janes street 2",
      "Name" : "Jane Doe",
      "Phone" : "87654321"
    },
    "SWhJ5CiJsKfvPOoG5MMSiLZlMC82" : {
      "Address" : "Johns street 1",
      "Name" : "John Doe",
      "Phone" : "12345678"
    }
  }
}    

我还想在Firebase的“信息”节点中实现地址和电话,但是首先我需要使其工作。.

1 个答案:

答案 0 :(得分:0)

尝试一下,从firebase读取时对我来说很好用:

  let user = Auth.auth().currentUser!.uid

ref?.child("users").child(user).observeSingleEvent(of: .value, with: { (snapshot) in

            // Get user info
            let value = snapshot.value as? NSDictionary
            let name = value?["Name"] as? String ?? ""

            self.nameFromFirebase = name
            // ...
        }) { (error) in
            print(error.localizedDescription)
        }
}