When I try to run the following code on a Simulator (also on a Device, the result is the same) I have a problem: the function executes first the part 2 of the following code (the comments are there just to have a reference, the code itself is entirely in the viewDidLoad. Just to be clear) and then it executes the part 1 (the firebase part). I need the ref.child.... function to be performed before the other function because the "createAlbums" func needs the albums taken from my database (So a completion block would be perfect, but that function doesn't allow me to put any).
I thought about a pair of solutions:
A way to add a completion block (remember that the ref.child... func is like a cycle so it will print the entire "albums" array for every single value that it finds on the database.
Create a Int var and make the 2 part of the code run only if the value of the var is the same as the number of values of "Albums" in the database, so it will fill up the local "Albums" array.
Use two different functions: the the viewDidLoad and the viewDidAppear. As I know, the second one will be performed after the first one.
Which one is the best solution? Is there any better solution? I also ask you to make suggests on how I can create my own solutions, because I can logically arrive to the point, but I'm not sure to be able to develop them in Xcode.
Just to summarize the entire thread: how can I make the 2 part of the following code run after the 1 part? And why does it run before, even if the order of writing is correct and the compiler runs from the line 1 to the last line?
Thank you for your help and sorry for my bad English, I hope that you can understand everything, unfortunately trying to explain a "complex" problem in English is not always easy.
But I think that the moderators will be great as always to make some corrections!
// 1
let ref = Database.database().reference()
var albums: [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
ref.child("Albums").observe(.childAdded) { (snapshot) in
albums.append(snapshot.key)
print("\(albums)")
print("Test print")
}
// 2
createAlbums()
setupConstraints()
}