无法检索数据并在UIBarButton - Firebase Swift 3中使用它

时间:2016-10-15 01:25:07

标签: ios firebase firebase-realtime-database swift3 uibarbuttonitem

我试图检索用户的用户名并将其保存到变量中,但每当我运行代码时都没有任何反应。这是我的Firebase布局: enter image description here

这是我的viewDidAppear()

中的代码
let uid = FIRAuth.auth()?.currentUser?.uid
let ref:FIRDatabaseReference!
ref = FIRDatabase.database().reference().root.child("users").child("\(uid)")
ref.observeSingleEvent(of: .value, with: { snapshot in
    print("test")
    if !snapshot.exists() { return }

    let user = (snapshot.value as? NSDictionary)?["name"] as? String ?? ""
    print(user)
    let username = UIBarButtonItem(title: user, style: UIBarButtonItemStyle.plain, target: self, action: nil)
    let picture = UIBarButtonItem()
    self.navigationController!.navigationItem.rightBarButtonItem = username
})

1 个答案:

答案 0 :(得分:3)

尝试使用: -

FIRDatabase.database().reference().root.child("users").child("\(FIRAuth.auth()!.currentUser!.uid)")observeSingleEvent(of: .value, with: { snapshot in
   print("test")
   if let snapDict = snapshot.value as? [String:AnyObject]{
          let user = snapDict["name"] as! String
          print(user)
          let username = UIBarButtonItem(title: user, style: UIBarButtonItemStyle.plain, target: self, action: nil)
          let picture = UIBarButtonItem()
          self.navigationItem.rightBarButtonItem = username
        } else {
           print("No such user exists!.")
      }
 })