Reputation: 11
I'm working on a patient/inventory management software on SwiftUI and I decided to ditch CoreData to go with Firebase. It seems to be less of a hassle but it's still a learning curve for me as a beginner. A dev helped me out initially to create and get the patients on the API patient file, but now that I am trying to update the data, I can't seem to figure out what to write...
I went through multiple tutorials and they all seem to be using the db.collection way of doing things.
Here is my code
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)
}
}
}
Thank you very much
Upvotes: 0
Views: 265
Reputation: 7254
I'd recommend using Firebase's Codable support, as this will make your code much more readable and maintainable.
For this, your Patient
should be a struct
that conforms to Codable
, like so:
struct Patient: Identifiable, Codable {
@DocumentID var id: String?
var firstName: String
var lastName: String
var address: String
// ...
}
Then, to fetch all patients from a collection (or those meeting certain criteria), use Firestore's snapshot listener:
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)
}
}
}
To add new patients, first create a new patient:
let patient = Patient(firstName: "Jane", lastName: "Appleseed", /* other attributes go here */)
And then add it to the collection like this:
func addPatient(patient: Patient) {
do {
let _ = try db.collection("patients").addDocument(from: patient)
}
catch {
print(error)
}
}
More details about this in my article here.
Upvotes: 5