Reading data from Firestore in Swift

266 views Asked by At

I am currently developing an IOS app, and I need a database! I've chosen the google firestore! I need to read some fields I create that have subfields! Something like this:

db.collection("usersorders").document(uid).collection("order").addDocument(data: ["items":0, "order":["Book1":0,"Book2":0,"Book3":0]]){ (error) in
                
                if error != nil {
                    // Show error message
                    print("Error saving user data")
                }
            }

Where I need to read the "Book1" value for example! I've looked in a lot of places, but I can't seem to find what I am looking for. Read subfields, from a field of a document!

@IBAction func AddtoCart(_ sender: Any) {
    let uid = user!.uid
    let docRef = db.collection("usersorders").document(user!.uid).collection("order").document()


    docRef.getDocument(source: .cache) { (document, error) in
        if let document  = document {
            let Book1  = document.get("Book1")
            let Items = document.get("items")
            
            let Book1now = Book1 as! Int + 1
            let Itemsnow = Items as! Int + 1
            
            
                  
        
}
    }}

This is what I have been doing but it doesn't work! After writing the code to update the database with the Items/Book1 now values it just doesn't update! Please Help me

1

There are 1 answers

2
Frank van Puffelen On BEST ANSWER

Given that your document data looks like this:

["items":0, "order":["Book1":0,"Book2":0,"Book3":0]]

You'll first need to access the order field in your document, before you can then find an item in that field

let order = document.get("order")

As far as I can see, this makes order a dictionary, so you can get the specific value from it with:

let book1 = order["Book1"] as Int