I had a problem with fetching data, seems to be working now, but instead of observing .childAdded, i need to observe value.
My Current code function is:
func fetchJobs() {
ref.child("jobposts").observe(.childAdded) { (snapshot) in
guard let dictionary = snapshot.value as? [String:Any] else { return}
var job = JobData()
job.title = (dictionary["title"] as! String) <-- Error in any of the job.*
job.company = (dictionary["company"] as! String)
job.city = (dictionary["city"] as! String)
job.salary = (dictionary["salary"] as! String)
job.creator = (dictionary["creator"] as! String)
self.jobs.append(job)
}
}
When i change .observe(.childAdded) to .observe(.value) i get an error :
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Any ideas what could cause this?
Using print(dictionary) prints all the documents, maybe i need to map them somehow? Thank you in advance
CodePudding user response:
When you observe a .value event for a list of nodes, you need to loop over snapshot.children
to get the individual nodes. From the documentation on listening for value events for lists:
_commentsRef.observe(.value) { snapshot in
for child in snapshot.children {
...
}
}
The ...
is where your current code inside the .childAdded
listener goes.