Zenman C
Zenman C

Reputation: 1723

Observer in Firebase not being called in swift app

I have written a method - checkUserStatus - in swift which checks if the user stored in firebase is an 'admin' or 'creator'. If they are then they can see the 'upload button'. The function is called in viewDidLoad as follows:

override func viewDidLoad() {
    super.viewDidLoad()
checkUserStatus()
}

The method is as follows:

func checkUserStatus() {
    let currentUserID = Auth.auth().currentUser?.uid
    //get the role of the current user to see if they have admin priveleges
    let userRef = Database.database().reference().child("users").child(currentUserID!)

    userRef.observe(.value, with: { (snapshot) in
        let dictionary = snapshot.value as! [String: Any]
        let role = dictionary["role"] as! String
        self.retrievedRole = role
    }, withCancel: nil)

    print("retrieved role is \(retrievedRole)")
    //only those users who are admin or creators can see upload button
    if (retrievedRole == "admin") || (retrievedRole == "creator") {
        uploadButton.isHidden = false
    } else {
        uploadButton.isHidden = true
    }
}

However, when I step through the method I can see that the observer is never used and jumps straight to the 'print' line which indicates that the retrievedRole variable is empty. The button is therefore always hidden. What have I missed that the observer is not used? Be grateful for any suggestions.

The variable for retrievedRole is declared at the top of the viewController as follows:

var retrievedRole = ""

Upvotes: 0

Views: 131

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You need to embed the check block inside the callback as it's call is asynchronous

userRef.observe(.value, with: { (snapshot) in
    let dictionary = snapshot.value as! [String: Any]
    let role = dictionary["role"] as! String
    self.retrievedRole = role

    print("retrieved role is \(retrievedRole)")
    //only those users who are admin or creators can see upload button
    if retrievedRole == "admin" || retrievedRole == "creator" {
       uploadButton.isHidden = false
    } else {
       uploadButton.isHidden = true
    }
}, withCancel: nil)

Upvotes: 1

Related Questions