【问题标题】:Retrieving Data from Firebase under ChildByAutoId and adding to array - Xcode - Swift在 ChildByAutoId 下从 Firebase 检索数据并添加到数组 - Xcode - Swift
【发布时间】:2020-01-29 09:03:05
【问题描述】:

这是我的 Firebase 数据库:

我正在尝试获取“Tgb9MyxTfdTRd9tQhInsjNRXoPL2”下所有购买和数量的数据并添加到数组中。

这是我的代码:

    func fetchPurchase(withUID uid: String, completion: @escaping (Purchase) -> ()) {
        Database.database().reference().child("purchases").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in


        guard let dict = snapshot.value as? [String: Any] else { return }
            print("dict-->", dict)
        let purchase = Purchase(uid: uid, dictionary: dict)
            print("purchase-->", purchase)
        completion(purchase)
    }) { (err) in
        print("Failed to fetch purchase from database:", err)
    }
}

这是print("dict-->", dict)的打印输出:

dict--> ["-LzjaFBgD3ATl7e8uR2-": {
purchase = "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0Lzk4OTUzMjEyODM=";
quantity = 1;
}, "-LzjaFBiAmrj4m3ZS8m4": {
purchase = "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0Lzk4OTUzMDk2OTk=";
quantity = 2;
}]

这是print("purchase-->", purchase)的打印输出:

 purchase--> Purchase(uid: "Tgb9MyxTfdTRd9tQhInsjNRXoPL2", purchases: "", quantities: "")

value dict 保存了我需要的数据,但我无法将数据放入数组中显示?

如何将采购和数量数据放入他们自己的数组中?

请帮忙!

【问题讨论】:

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


    【解决方案1】:
        func fetchPurchase(withUID uid: String, completion: @escaping (Purchase) -> ()) {
                Database.database().reference().child("purchases").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
    
                if snapshot.childrenCount > 0 {
                    self.YourArrayList.removeAll()
                     for dict in snapshot.children.allObjects as! [DataSnapshot]
                        let purchase = Purchase(uid: uid, dictionary: dict)
                        self.YourArrayList.append(purchase)
                    }
    
                }
                completion(purchase)
            }) { (err) in
                print("Failed to fetch purchase from database:", err)
            }
        }
    
    }
    

    【讨论】:

    • for 循环中的 i 在哪里?
    • 不是什么大问题,但您已将所有快照子节点转换为[DataSnapshot](即点对点),但您的循环变量称为dict,这看起来有点误导就像 Purchase 对象期望的是 Dictionary,而不是 DataSnapshot。为了清楚起见,可能应该将其称为 childSnap 或 snap 或将其转换为 dict [String: Any]。除此之外,很好的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多