【问题标题】:Get value property using Firebase in Swift在 Swift 中使用 Firebase 获取值属性
【发布时间】:2016-08-02 09:24:45
【问题描述】:

使用 Firebase 我试图获得属于“品牌”的“产品”价值。例如,如果我单击“品牌”-“CATCH”所在的单元格,我想显示所有“CATCH”产品的新tableView。我怎样才能做到这一点?这是 Firebase 结构:

在这里,我得到了所有这样的“品牌”名称:

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()
            }
        }
    })
}

像这样我正在尝试使用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()
            }
        }
    })
}

这就是我检测单元格点击的方式:

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

}

我还有 2 个表格视图和自定义单元格来显示“产品”

细胞检测对吗?如何做到这一点?我在互联网上没有通过谷歌搜索看到任何内容,但也许你知道一些链接。

【问题讨论】:

    标签: ios swift uitableview firebase firebase-realtime-database


    【解决方案1】:

    我认为要在一个数组中获取所有值和键,您需要使用[[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"])")
    }
    

    【讨论】:

    • “同一时间”是什么意思?在我看来,我首先加载品牌,然后加载产品:D
    • 这意味着只有一个观察者和一个数组..你可以得到两个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 2015-04-26
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多