如何使用 SwiftUI 更新 Firebase 中的集合?

AMc*_*hou 1 foundation firebase swift google-cloud-firestore swiftui

我正在 SwiftUI 上开发患者/库存管理软件,我决定放弃 CoreData,转而使用 Firebase。这似乎不那么麻烦,但对我作为初学者来说仍然是一个学习曲线。开发人员最初帮助我创建并获取 API 患者文件中的患者,但现在我正在尝试更新数据,我似乎不知道该写什么......

我浏览了多个教程,它们似乎都在使用 db.collection 做事方式。

这是我的代码

import Foundation
import FirebaseFirestore
class PatientAPI {
    
    func createPatient(firstName: String, lastName: String, address: String, postCode: String, phoneNumber: String, onSuccess: @escaping(_ successMessage: String) -> Void) {
     
        let testPatient = PatientModel.init(firstName: firstName, lastName: lastName, address: address, postalCode: postCode, phoneNumber: phoneNumber)
       
        
        
        guard let dict = try? testPatient.toDictionary() else {return} /
       
        API.FIRESTORE_COLLECTION_PATIENTS.addDocument(data: dict)
        onSuccess("Done")
    }
    

    
    func getPatients(onSuccess: @escaping(_ patients: [PatientModel]) -> Void, onError: @escaping(_ errorMesage: String) -> Void) {
        
       
        API.FIRESTORE_COLLECTION_PATIENTS.getDocuments { (snapshot, error) in
            if let error = error {
                onError(error.localizedDescription)
                return
            }
            
            
            guard let snap = snapshot else {return}
            
            var patients = [PatientModel]()
            
            
           
            for document in snap.documents {
                let dict = document.data()
                guard let decodedPatient = try? PatientModel.init(fromDictionary: dict) else {return}
                patients.append(decodedPatient) 
                
            }
            onSuccess(patients) 
        }
    }
 
   
}
Run Code Online (Sandbox Code Playgroud)

非常感谢

Pet*_*ese 5

我建议使用 Firebase 的 Codable 支持,因为这将使您的代码更具可读性和可维护性。

为此,您Patient应该是struct符合 的Codable,如下所示:

struct Patient: Identifiable, Codable {
  @DocumentID var id: String?
  var firstName: String
  var lastName: String
  var address: String
  // ...
}
Run Code Online (Sandbox Code Playgroud)

然后,要从集合中获取所有患者(或满足特定条件的患者),请使用 Firestore 的快照侦听器:

func fetchData() {
  db.collection("patients").addSnapshotListener { (querySnapshot, error) in
    guard let documents = querySnapshot?.documents else {
      print("No documents")
      return
    }
      
    self.books = documents.compactMap { queryDocumentSnapshot -> Patient? in
      return try? queryDocumentSnapshot.data(as: Patient.self)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

要添加新患者,首先创建一个新患者:

let patient = Patient(firstName: "Jane", lastName: "Appleseed", /* other attributes go here */)
Run Code Online (Sandbox Code Playgroud)

然后像这样将它添加到集合中:

func addPatient(patient: Patient) {
  do {
    let _ = try db.collection("patients").addDocument(from: patient)
  }
  catch {
    print(error)
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的文章here中有关此的更多详细信息。