首页 > 解决方案 > 通过 uid 向 Firestore 显示数据

问题描述

我很难从 Firebase 实时数据库切换到 Firestore。我正在尝试将我的 budgetData 数组显示到表格视图上。我可以让用户 uid 打印,但是数据不会附加到我的 budgetData 数组并显示在表格视图上。现在我只是想保存标题,看看是否可以将它保存到数组并显示。loadData() 函数也不起作用。在此处输入图像描述

  var budgetData: [Transaction] = [ ] 

  func loadUserInfo() {
      let db = Firestore.firestore()
    db.collection("Categories").whereField("uid", isEqualTo: String(describing: Auth.auth().currentUser!.uid)).addSnapshotListener({ (querySnapshot, error) in
        guard let documents = querySnapshot?.documents else {
            return
        }
        
        self.budgetData = documents.compactMap({ (queryDocumentSnapshot) -> Transaction? in
            let data = queryDocumentSnapshot.data()
            let title = data["title"] as? String ?? ""
            return Transaction(title: title, dateInfo: "", image: UIImage.gymIcon, amount: 45, annualPercentageRate: 45, trailingSubText: "", uid: "")
        })
    })
         override func viewDidLoad() {

    guard let user = Auth.auth().currentUser?.uid else { return }
    print("user id:\(user)")
    super.viewDidLoad()
    loadUserInfo()
 //loadData()
     }


     func loadData() {
    let db = Firestore.firestore()
    db.collection("Categories").whereField("uid", isEqualTo: String(describing: Auth.auth().currentUser!.uid)).getDocuments() {querySnapshot, error in
        if let error = error {
            
            
            print(error.localizedDescription)
        }else {
            self.budgetData = querySnapshot!.documents.flatMap({Transaction(dictionary: $0.data())})
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
        
    }
    
}
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.budgetData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: CategoryCell.identifier) as? CategoryCell else { return UITableViewCell() }
    
    let data = budgetData[indexPath.row]
    cell.label.text = data.title
    return cell
}



 protocol DocumentSerializable {
init?(dictionary:[String:Any])
  }

   struct Transaction {
var title: String
var dateInfo: String
var image: UIImage
var amount: Double
var annualPercentageRate: Double?
var trailingSubText: String?
var uid: String?


var dictionary:[String:Any]{
    
    return [
        "title": title,
        "dateInfo":dateInfo,
        "amount":amount,
        "annualPercentageRate":annualPercentageRate,
        "trailingSubText":trailingSubText,
        "uid": uid
    ]
}

 }

   extension Transaction : DocumentSerializable {

init?(dictionary: [String:Any]){
    guard let title = dictionary["title"] as? String,
          let dateInfo = dictionary["dateInfo"] as? String,
          let image = dictionary["image"] as? UIImage,
          let amount = dictionary["amount"] as? Double,
          let annualPercentageRate = dictionary["annualPercentageRate"] as? Double,
          let trailingSubText = dictionary["trailingSubText"] as? String,
          let uid = dictionary["uid"] as? String else {return nil}
    self.init(title: title, dateInfo: dateInfo, image: image, amount: amount, annualPercentageRate: annualPercentageRate, trailingSubText: trailingSubText, uid: uid)
    
          
    
}
}

标签: iosswiftgoogle-cloud-firestore

解决方案


推荐阅读