问题
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