0

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
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Karliene
  • 147
  • 1
  • 3
  • 10

1 Answers1

0
func initialiseTicketsList(completionHandler: @escaping ([String]) -> Void) {
    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]
            var toWatchMoviesListInitial: [String] = [] //local variable
            for (_,myValue) in userDict! {
                if myValue.contains("ignore"){
                }
                else{
                    print(type(of: myValue))
                    toWatchMoviesListInitial.append(myValue)
                }
            }
            completionHandler(toWatchMoviesListInitial) // callback invoked.
        }
    }, withCancel: nil)
}

// wherever you call initialiseTicketsList, call with completionHandler
initialiseTicketsList(completionHandler: {movieList in
 self.toWatchMoviesList = movieList // or append based on your usecase.
}

Please read about closure and @escaping at here

Dinesh Balasubramanian
  • 20,532
  • 7
  • 64
  • 57