How to setup a Bar Button with a value of firebase?

China☆狼群 提交于 2021-01-29 08:00:39

问题


I want to check if the user is a admin or not. If the user is a admin, I want to show a bar button. If not, the bar button should be hidden.

I call the following code in viewDidLoad:

@IBOutlet weak var beitraegeMelden: UIBarButtonItem!
var admin = false

func setupBarButton() {
    observeAdmin()
    if admin == true {
        self.beitraegeMelden.isEnabled = true
        self.navigationItem.rightBarButtonItem = self.beitraegeMelden
    } else {
        self.beitraegeMelden.isEnabled = false
        self.navigationItem.rightBarButtonItem = nil
    }
}

func observeAdmin() {
    guard let currentUserUid = UserApi.shared.CURRENT_USER_ID else { return }
    let REF_ADMIN = Database.database().reference().child("users").child(currentUserUid).child("admin")
    REF_ADMIN.observeSingleEvent(of: .value) { (admin) in
        let adminRecht = admin.value as? Bool
        if adminRecht == true {
            self.admin = true
        } else {
            self.admin = false
        }
    }
}

Here my database structure of the actually logged in user:

users
    currentUid
        admin: true 

The admin value never gets true. Thanks in advance for your help!


回答1:


You need a completion as the call to firebase is asynchronous

func observeAdmin(completion:@escaping((Bool) -> () )) {
    guard let currentUserUid = UserApi.shared.CURRENT_USER_ID else { return }
    let REF_ADMIN = Database.database().reference().child("users").child(currentUserUid).child("admin")
    REF_ADMIN.observeSingleEvent(of: .value) { (admin) in
       completion( (admin.value as? Bool) ?? false )
    }
}

Call

observeAdmin { (res) in 
   self.beitraegeMelden.isEnabled = res    
   self.navigationItem.rightBarButtonItem = res ? self.beitraegeMelden : nil
}


来源:https://stackoverflow.com/questions/53979516/how-to-setup-a-bar-button-with-a-value-of-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!