Reputation: 2261
My app retrieves data from the Firebase Database, puts it in a tableView using my CustomCell, and my goal is when a cell is tapped, I want the string which is stored in a label in that tapped cell.
so I'm trying this for couple days now, and the provided solutions mostly apply only to static cells, where content is not dynamically loaded, like it is here. The options I tried:
indexPath
: This turned out to be difficult, since the array was not properly synced with Firebase, leading to a wrong order in the indexPath
. I have not found a library yet which keeps the array synced, however general consensus seems to be that I should stay away from arrays when using Firebase.cellForRowAtIndexPath
or dequeueReusableCellWithIdentifier
, which also made that a difficult solution.What I have so far:
func getQuery() -> FIRDatabaseQuery {
let myTopPostsQuery = (ref.child("posts"))
return myTopPostsQuery
}
override func viewDidLoad() {
super.viewDidLoad()
self.ref = FIRDatabase.database().reference()
dataSource = FirebaseTableViewDataSource.init(query: getQuery(),prototypeReuseIdentifier: "Cellident", view: self.tableView)
dataSource?.populateCellWithBlock { (cell: UITableViewCell, obj: NSObject) -> Void in
let customCell = cell as! CustomCellTableViewCell
let snap = obj as! FIRDataSnapshot
let childString = snap.value as! [String : AnyObject]
customCell.textLabel.text = String(childString)} // << This is what I need to access in didSelectRowAtIndexPath
}
tableView.dataSource = dataSource
tableView.delegate = self
}
My question is now what would be the most practical way to go, and if there is a solution I have not considered yet?
Upvotes: 1
Views: 249
Reputation: 1028
Do this in didSelectRowAtIndexPath TableViewDelegate method
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let path: NSIndexPath = indexPath
let source = dataSource
let snapshot: FIRDataSnapshot = (source?.objectAtIndex(UInt(path.row)))! as! FIRDataSnapshot
let childString = snapshot.value as! String
}
Upvotes: 1