Until now, I stored the categories data in an array and displayed them.
var categories: [BusinessCategory] = [
.init(id: "id1", name: "Doctor", image: "https://icon.url"),
.init(id: "id2", name: "Restaurant", image: "https://icon.url"),
.init(id: "id4", name: "Citizen Service", image: "https://icon.url"),
.init(id: "id5", name: "Barber Shop", image: "https://icon.url"),
.init(id: "id6", name: "Corona-Test", image: "https://icon.url")
]
I would like to move this into a Database by using Firestore. After storing the categories in different documents, the format is of course different when using getDocuments()
func getAllCategories(){
database.collection("categories").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.data())")
}
}
}
}
The results of the getDocuments()
call is:
["image": https://icon.url, "name": Restaurant, "id": 2]
["image": https://icon.url, "name": Citizen Service, "id": 3]
["image": https://icon.url, "name": Doctor, "id": 1]
["image": https://icon.url, "name": Corona-Test, "id": 5]
["image": https://icon.url, "name": Barber Shop, "id": 4]
Any ideas on how to do it the best way? I need to transform all categories
["image": https://icon.url, "name": Doctor, "id": 1]
into
.init(id: "id1", name: "Doctor", image: "https://icon.url"),
CodePudding user response:
- You can create a struct called
BusinessCategories
for storing each of the category item, within your project. You will need to useCodable
Protocols and usesetData
function (write function) to create necessary documents in the Firestore.
struct BusinessCategories: Codable, Identificable {
var id: String
var name: String
var image: String
enum CodingKeys: String, CodingKey {
case id
case name
case image
}
}
After storing data model
BusinessCategories
in the Firestore, you can retrieve them viagetDocuments
orsnapshotlisteners
whichever you prefer.Once you retrieve/read the
BusinessCategories
document From Firestore, you can decode (use for-loop to convert document into the struct you already created) the Firestore data into the struct which you already created beforehand.
So far, this is the cleanest and the usual way to perform the task you desired. you may also refer to this tutorial - https://www.youtube.com/watch?v=3-yQeAf3bLE
Otherwise, if you really want to clump the BusinessCategories into an array. You will keep encountering the problem you are currently facing and you will need (difficult, I think) customization to convert the data, definitely an uphill task.