Reputation: 161
I am using an array stored in a structure to store the entries from a firebase database. I am successfully able to load the data as I could print out each of the database's items. However, an array called allMovies is somehow empty even though I just filled it with data from firebase.
Why is this happening?
Here is my code:
The global structure that holds my array and its changes are visible throughout the program.
struct GlobalMovies {
static var allMovies:[Movies] = []
static var hotMovies:[Movies] = []
static var upcomingMovies:[Movies] = []
}
The functionality that reads data from my firebase. As mentioned earlier, I am successfully able to read the data.
var ref:DatabaseReference?
var databaseHandle:DatabaseHandle?
databaseHandle = ref?.child("Movies").observe(.childAdded, with: { (snapshot) in
if let userDict = snapshot.value as? [String:Any] {
GlobalMovies.allMovies.append(Movies(name: userDict["name"]! as! String ,
rating: userDict["rating"]! as! String,
length: userDict["length"]! as! String,
genre: userDict["genre"]! as! String ,
cast : userDict["cast"] as! [String],
cinemas : userDict["cinemas"] as! [String],
releaseDate: userDict["releaseDate"]! as! String,
director: userDict["director"]! as! String,
description: userDict["description"]! as! String ,
image: userDict["image"]! as! String,
isHot: userDict["isHot"]! as! Bool,
isUpcoming: userDict["isUpcoming"]! as! Bool))
self.table.reloadData()
}
})
print(GlobalMovies.allMovies.count) //prints out 0 when it shouldn't
My json file:
{
"Movies": {
"Movie1" : {
"name": "The Incredible Hulk",
"rating": "4/5",
"length": "120 minutes",
"genre": "Fantasy",
"cast" : ["Lisa Simpson", "Peter Griffin"],
"cinemas": ["A", "B"],
"releaseDate": "12/05/2018",
"director": "Mike Lancaster",
"description" : "Lorem Ipsum",
"image": "default",
"isHot": true,
"isUpcoming": false
},
"Movie2" : {
"name": "Star Wars",
"rating": "5/5",
"length": "120 minutes",
"genre": "SciFi",
"cast" : ["Lisa Simpson", "Peter Griffin"],
"cinemas": ["A", "B"],
"releaseDate": "12/05/2018",
"director": "Mike Lancaster",
"description" : "Lorem Ipsum",
"image": "default",
"isHot": true,
"isUpcoming": false
}
}
}
Upvotes: 0
Views: 104
Reputation: 1456
The reason is because the firebase fetches the data asychronusly so when you do the print it hasn't yet fetched the data, but after some time it will fetch them. What you have to do is to do is print the data when the fetching has finished
Upvotes: 1