Как Firebase получить данные ниже UID и автоматического идентификатора в Swift - PullRequest
0 голосов
/ 18 мая 2019

[введите описание изображения здесь] [1] Я пытаюсь получить конкретные данные из базы данных.Я хотел бы прочитать все данные в product_list

Моя база данных

Это то, что я пытаюсь, но когда я печатаю listName.Это выглядит так: listName = nil

 let refList = Database.database().reference().child("Users/Sellers")
        refList.observe(DataEventType.value, with:{(snapshot) in
            if snapshot.childrenCount>0{
                self.listProduct.removeAll()

                for lists in snapshot.children.allObjects as! [DataSnapshot]{
                    let userList = lists.value as? [String: AnyObject]
                    let listName = userList?["name"]
                    let listDetail = userList?["detail"]
                    let listPrice = userList?["price"]
                    print("key = \(listName)")

                    let list = ListModel(name: listName as! String?, detail: listDetail as! String?, price: listPrice as! String?)

                    self.listProduct.append(list)
                }
                self.tableList.reloadData()
            }

        })
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell

        let list: ListModel
        list = listProduct[indexPath.row]

        cell.lblName.text = list.name
        cell.lblDetail.text = list.detail
        cell.lblPrice.text = list.price

        return cell
    }

У него есть 4 вещи, которые я хочу получить

(подробности, имя, цена и product_image_url)

1 Ответ

0 голосов
/ 18 мая 2019

Прямо сейчас ваш код зацикливается на дочерних узлах /Users/Sellers, которые являются узлами каждого отдельного пользователя. Похоже, вы хотите включить все узлы в свойство product_list каждого пользователя, что требует дополнительного вложенного цикла:

let refList = Database.database().reference().child("Users/Sellers")

refList.observe(DataEventType.value, with:{(snapshot) in
    if snapshot.childrenCount>0{
        self.listProduct.removeAll()

        for user in snapshot.children.allObjects as! [DataSnapshot]{
            let productList = user.childSnapshot(forPath: "product_list")
            for product in productList.children.allObjects as! [DataSnapshot]{
              let userList = product.value as? [String: AnyObject]
              let listName = userList?["name"]
              let listDetail = userList?["details"] // NOTE: also fixed a typo here
              let listPrice = userList?["price"]
              print("key = \(listName)")

              let list = ListModel(name: listName as! String?, detail: listDetail as! String?, price: listPrice as! String?)

              self.listProduct.append(list)

            }
        }
        self.tableList.reloadData()
    }

})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...