【问题标题】:Unable to retrieve data and use it in a UIBarButton - Firebase Swift 3无法检索数据并在 UIBarButton 中使用它 - Firebase Swift 3
【发布时间】:2017-02-24 12:40:27
【问题描述】:

我正在尝试检索用户的用户名并将其保存到变量中,尽管每当我运行代码时都没有任何反应。这是我的 Firebase 布局:

这是我的代码,位于我的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
})

【问题讨论】:

  • 如果您在调试器中单步执行代码,会发生什么?它会进入observeSingleEvent 回调吗?
  • 代码运行,但是当我尝试打印用户名时没有任何结果(打印(用户))编辑:代码运行,但代码没有做任何事情。

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


【解决方案1】:

尝试使用:-

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!.")
      }
 })

【讨论】:

  • 这是正确检索用户名,但它没有显示在导航控制器上。也许我设置不正确?
  • 很好的答案@Dravidian !
猜你喜欢
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 2016-08-12
  • 2016-10-15
  • 2017-04-17
  • 1970-01-01
相关资源
最近更新 更多