Search code examples
iosswiftfirebasetableviewcell

Swift - How to save data to Firebase from multiply selected cells in TableView?


I need to save all data from selected cells in tableView to Firebase Database. In cells I have just labels, no buttons, actions or textfields. I want when I select multiply cells, then click to saveButton and all data from cells to store on Firebase.


Solution

  • If you take a look at Apples documentation here, you will see a section that discusses how to properly handle multiple row selections.

    Like I said in my comment though, you will need to use the

    tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    

    method, and inside that function append the indexPath.row value to an array you can reference outside of that function call (so you can set it up as a instance property of your view controller, for example). Once all desired rows have been selected, when the user clicks the send button, you can loop through the index array, then pull the necessary record from your data source and upload it to Firebase, or you can populate a temporary array and send the whole array to Firebase, whatever works best for you.

    Here's a simple example of what I mean

    var indexArray: [Int] = []
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      
       indexArray.append(indexPath.row)
       
    }
    
    func sendToFirebase() {
     for index in indexArray {
      //... get record from datasource and send to Firebase
     }
    }
    

    Make sure you take a look at Apple's documentation though, because it discusses deselecting the rows and using check marks as best practice for displaying selected rows.