ffritz
ffritz

Reputation: 2261

Access CustomCell content coming from Firebase in didSelectRowAtIndexPath

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:

  1. Using an Array to store the contents, then get them in combination with 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.
  2. Using delegation or closures like suggested here: Because I am using the FirebaseUI to populate my cells, I don't have the two methods 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

Answers (1)

sm abbas
sm abbas

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

Related Questions