0
 func callData() -> String? {
    var name: String = ""
    var ref: DatabaseReference!
     ref = Database.database().reference()
    ref.child("reyddatbase").child("MovieData").child("InitialMovieData").child("Ariel").child("movie_name").observeSingleEvent(of: .value, with: { (snapshot) in
        name = ((snapshot.value) as! NSString) as String;
        
        
        print("\(name)") // prints what I need
    })
    print("\(name)") // prints nothing??
    return "\(name)" // returns nothing?
}

I am attempting to read data from a database based in Firebase. I would like to simply display the text on screen which I can do from content view.

However the print statement inside the ref.child shows my title in console, while my print statement outside of it remains an empty string. I am not sure why the different print statements do not yield the same result.

I am very new to swift and have taught myself to this point. I presume there is a simple solution to my problem. Thank you in advance for the help!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    This is working as intended: the data is loaded from Firebase asynchronously, since it may have to come from the server. Instead of blocking the user from using the app, your main code continues (and the `return "\(name)"` runs) straight away. Then when the data is available your closure is called and runs the `name = ((snapshot.value) as! NSString) as String`. For this reason, all code that needs the data needs to be in the completion handler, and you can't return a value. You can pass in your own closure handler however, or use a dispatcher. I'll add some links. – Frank van Puffelen Jul 13 '20 at 04:01
  • Well said...... – El Tomato Jul 13 '20 at 04:06

0 Answers0