Tarvo Mäesepp Tarvo Mäesepp - 4 months ago 21
iOS Question

Passing value from Firebase from one tableView to another

I am trying to pass value I get from Firebase to another

tableView
. I get 2 values from Firebase - "Brands" and "Products". I am trying to make like car app. If you click on Ford then new
tableView
will appear and shows all the Ford models. This is what I've done so far.

like this I get Brands from Firebase:

func parseSnusBrands(){
let ref = FIRDatabase.database().reference().child("Snuses").child("Brands")

ref.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if snapshot.exists() {
if let all = (snapshot.value?.allKeys)! as? [String]{
for a in all{
if let products = snapshot.value![a] as? [[String:String]]{
self.snusBrandsArray.append(["key":a,"value":products])
}
}
self.snusBrandsTableView.reloadData()
}
}
})
}


And like this I detect which cell is clicked and print the product that belongs to the clicked Brand:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
print("products at \(indexPath.row) --> \(snusBrandsArray[indexPath.row]["value"])")

}


How to pass the
(snusBrandsArray[indexPath.row]["value"])
to new
tableView
? I tried using segues and looking for tutorials like "How to pas value between viewControllers" but I am out of luck. Right now I have 2
tableViewController.swift
files and one
tableViewCustomCell.swift
file. Do I need some more files?

Answer

For send data, first of all declare your variable in 2nd view controller..

  var productsValue = [[String:String]]()

and in 1st viewcontroller

  var valueTopass = [[String:String]]()

Than in didSelectRowAtIndexPath, take a value in one valueTopass

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("products at \(indexPath.row)  --> \(snusBrandsArray[indexPath.row]["value"])")
    if let products = snusBrandsArray[indexPath.row]["value"] as? [[String:String]]{
        valueTopass = products
        performSegueWithIdentifier("toProducts", sender: self)
    }
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "toProducts") {
        var viewController = segue.destinationViewController as! SnusProductsTableViewController
        viewController.productsValue = valueTopass
        print(productValues)
    }
}