Answer the question
In order to leave comments, you need to log in
How to store values received asynchronously in a global array?
I am getting data from Firebase and I want to store it in an array of structures ( PostData ) so that I can populate the CollectionViewCell cells inside the TableViewCell through it. The problem is that I get the data, at some point I even manage to calculate it, but to just store it in an array and use it between classes - no chance :( Here is the code of the table where I want to receive data (Social.swift) :
var dataPosts = [PostData]()
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: self.view.bounds, style: .grouped)
tableView.delegate = self
tableView.dataSource = self
...
self.parsePosts() { tempData in
self.dataPosts = tempData
self.tableView.reloadData()
}
}
...
func parsePosts(completion: @escaping ([PostData]) -> Void) {
var tempData = [PostData]()
let databaseRef = Database.database().reference(withPath: "Посты")
databaseRef.observe(.value) { (snapshot, error) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let res = snap.value as! [String: Any]
let title = res["Заголовок"] as! String
let subtitle = res["Подзаголовок"] as! String
let img = res["URL"] as! String
let date = res["Дата"] as! String
tempData.append(PostData(title: title, subtitle: subtitle, imgURL: img, date: date))
}
DispatchGroup().notify(queue: .main) {
self.tableView.reloadData()
let postCell = PostCell()
postCell.dataForPosts = tempData
print(postCell.dataForPosts, "в старом классе" ) // Выводит, что нужно
}
completion(tempData)
}
}
var dataForPosts:[PostData] = []
...
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.PostCollectionID, for: indexPath)
print(self.dataForPosts, " - в другом классе ") // Выводит пустой массив
cell.layer.borderWidth = 5
cell.layer.cornerRadius = 20
return cell
}
Answer the question
In order to leave comments, you need to log in
If it’s very clumsy and primitive and practically never do it, then make Social a singleton and refer to it, and not to self, in print(self.dataForPosts, "- in another class "
) datasource for the table at the moment of initiating the datasource and then refer to the instance of the Social class already stored in the property.
... specify, ask, I can imagine how what I just wrote is seen from the outside, but now I don’t understand how to write otherwise.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question