如何使用 SwiftUI 更新 Firebase 中的集合?
How to update collection in Firebase using SwiftUI?
我正在 SwiftUI 上开发一个 patient/inventory 管理软件,我决定放弃 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)
}
}
}
非常感谢
我建议使用 Firebase 的 Codable 支持,因为这将使您的代码更具可读性和可维护性。
为此,您的 Patient
应该是符合 Codable
的 struct
,例如:
struct Patient: Identifiable, Codable {
@DocumentID var id: String?
var firstName: String
var lastName: String
var address: String
// ...
}
然后,要从集合中获取所有患者(或满足特定条件的患者),请使用 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)
}
}
}
要添加新患者,请先创建一个新患者:
let patient = Patient(firstName: "Jane", lastName: "Appleseed", /* other attributes go here */)
然后像这样将其添加到集合中:
func addPatient(patient: Patient) {
do {
let _ = try db.collection("patients").addDocument(from: patient)
}
catch {
print(error)
}
}
我的 article here 中有更多详细信息。
我正在 SwiftUI 上开发一个 patient/inventory 管理软件,我决定放弃 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)
}
}
}
非常感谢
我建议使用 Firebase 的 Codable 支持,因为这将使您的代码更具可读性和可维护性。
为此,您的 Patient
应该是符合 Codable
的 struct
,例如:
struct Patient: Identifiable, Codable {
@DocumentID var id: String?
var firstName: String
var lastName: String
var address: String
// ...
}
然后,要从集合中获取所有患者(或满足特定条件的患者),请使用 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)
}
}
}
要添加新患者,请先创建一个新患者:
let patient = Patient(firstName: "Jane", lastName: "Appleseed", /* other attributes go here */)
然后像这样将其添加到集合中:
func addPatient(patient: Patient) {
do {
let _ = try db.collection("patients").addDocument(from: patient)
}
catch {
print(error)
}
}
我的 article here 中有更多详细信息。