1

I try to get the values from Firebase and after that I want to print the second line of code executed and then true.

But the order is total wrong. What am I doing wrong?

override func viewDidLoad() {
        super.viewDidLoad()
        

        method(arg: true, completion: { (success) -> Void in
            print("Second line of code executed")
            if success { // this will be equal to whatever value is set in this method call
                  print("true")
            } else {
                 print("false")
            }
        })
        
    }
    func method(arg: Bool, completion: (Bool) -> ()) {
        let userID = Auth.auth().currentUser!.uid
        let database = Database.database().reference()
        database.child("user/\(userID)/abonniertePoi/").observe(.value, with: { snapshot in
            for child in snapshot.children.allObjects as! [DataSnapshot] {
                myFeed.myArray1.append(child.key)
            }
            print(myFeed.myArray1)
            
        })
        completion(arg)
    }

It first prints second line executed then does the Firebase request and then says true.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
submariner
  • 308
  • 1
  • 5
  • 23
  • That's because data is loaded from Firebase (and pretty much any modern cloud API) asynchronously. You'll want to move the `completion(arg)` to be **inside** the completion handler (likely right after you `print(myFeed.myArray1)`). Also see https://stackoverflow.com/q/31261500/, https://stackoverflow.com/a/41262940, https://stackoverflow.com/a/37925384 and more from https://stackoverflow.com/search?tab=votes&q=%5bfirebase-realtime-database%5d%5bswift%5d%20asynchronous – Frank van Puffelen Jul 03 '22 at 16:33
  • Thanks for the explanation. I looked at the sources you send but the explanation is way to complex. I didn't even understand what they did there. My code is much more simple so I don't understand how I can adopt it like in the links you sent. – submariner Jul 03 '22 at 18:24
  • As I said in my comment, you will need to move the `completion(arg)` to be **inside** the completion handler (likely right after you `print(myFeed.myArray1))`. – Frank van Puffelen Jul 04 '22 at 00:45
  • I tried it but then it says: Escaping closure captures non-escaping parameter 'completion' – submariner Jul 06 '22 at 18:46
  • I see some interesting results when I search for that error message. – Frank van Puffelen Jul 06 '22 at 19:02
  • I changed this line and it seems to work. Why is it so complicated one the links which you sent above? func method(arg: Bool, completion: @escaping (Bool) -> ()) { – submariner Jul 06 '22 at 19:18

0 Answers0