let ref = Database.database().reference(withPath: "items")
ref.observe(.value) { (snapshot) in
guard let dict = snapshot.value as? NSArray else { return }
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
dict.forEach { (value) in
do {
let itemData = try JSONSerialization.data(withJSONObject: value,options: .prettyPrinted)
let item = try decoder.decode(Item.self, from: itemData)
self.items.append(item)
}
catch let err {
print(err.localizedDescription)
}
}
print(self.items) // This
print(self.items[0]) // works
}
and trying to access items in tableview:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
itemType = String(describing: (self.items[indexPath.section].item_type)) // terminating with index out of range error
//...
}
The error occurs because the observe methods work asynchronously and executes later then tableview populates data.
How to solve this ?