Tarvo Mäesepp
Tarvo Mäesepp

Reputation: 4533

Get value property using Firebase in Swift

Using Firebase I am trying to get the "Product" value that belongs to the "Brand". For example if I click on cell where is "Brand"-"CATCH" I want to show new tableView with all the "CATCH" Products. How Can I achieve this? This is the Firebase structure:

enter image description here

Here I am getting all the "Brands" names like this:

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

    ref.queryOrderedByKey().observeEventType(.Value, withBlock: { (snapshot) in
        if snapshot.exists() {
            if let all = (snapshot.value?.allKeys)! as? [String]{
                self.snusBrandsArray = all
                self.snusBrandsTableView.reloadData()
            }
        }
    })
}

And like this I am trying to get the "Products" values using the allKeys:

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

    ref.queryOrderedByKey().observeEventType(.Value, withBlock: { (snapshot) in
        if snapshot.exists() {
            if let all = (snapshot.value?.allValues)! as? [String]{
                self.snusBrandsArray = all
                self.snusBrandsTableView.reloadData()
            }
        }
    })
}

This is how I detect the cell click:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
    parseSnusProducts()

}

I have 2 tableViews also and custom cell to show the "Products"

Is the cell detection right? How to achieve this? I don't see anything on the internet by Googling but maybe you know some links.

Upvotes: 1

Views: 1979

Answers (1)

Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

I think to get all values and keys in one array, you need to use [[String:AnyObject]]

var snusBrandsArray = [[String:AnyObject]]()

override func viewDidLoad() {
    super.viewDidLoad()
    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.yourtableview.reloadData()
            }
        }
    })
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //cell declaration
    print(snusBrandsArray[indexPath.row]["key"])
}

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

Upvotes: 3

Related Questions