jo1995
jo1995

Reputation: 414

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

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!

Upvotes: 0

Views: 33

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

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
}

Upvotes: 1

Related Questions