I've written code to retrieve data from my firebase database and to append it to an array called toWatchMoviesListInitial
. However upon printing out the value of toWatchMoviesListInitial
after appending the data, it prints out nothing.
I've been told this is because this is asynchronous. And to deal with this one can use completion handlers.
However, I'm new to swift and I do not know how to implement completion handlers. I would be grateful if you could show me how to go about it. Here is my code:
func initialiseTicketsList() {
ref = Database.database().reference()
let uid = Auth.auth().currentUser?.uid
ref?.child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let userDict = dictionary["watchList"] as? [String:String]
for (_,myValue) in userDict! {
if myValue.contains("ignore"){
}
else{
print(type(of: myValue))
self.toWatchMoviesListInitial.append(myValue)
}
}
}
}, withCancel: nil)
print(toWatchMoviesList) //prints empty when it shouldn't
}