glothais-kwl
glothais-kwl

Reputation: 181

Swiftui + Firestore - Cannot access field in Firestore

trying to access a specific field in Firestore, but can't seem to figure it out. In my document, I have a map like this:

data structure

The below is my code. Hour just returns nil for some reason. I've tried a number of different things including ["notificationTime"]["hour"], but can't seem to figure it out. Any idea? Thanks!

self.db.collection("routines").whereField("name", isEqualTo: routineName).getDocuments() { (querySnapshot, err) in
        if let err = err {
            print ("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                let hour = document.data()["notificationTime.hour"]
                print(hour)
                return
             }
        }
    }

Upvotes: 0

Views: 109

Answers (1)

Peter Friese
Peter Friese

Reputation: 7254

To read data from a map, use the following approach:

let db = Firestore.firestore()
db.collection("routines").whereField("name", isEqualTo: routineName).getDocuments() { (querySnapshot, err) in
  if let err = err {
    print("Error getting documents: \(err)")
  } 
  else if let querySnapshot = querySnapshot {
    for document in querySnapshot.documents {
      let results = document.data()
      if let notificationTime = results["notificationTime"] as? [String: Any] {
        let hour = notificationTime["hour"] as? Int ?? 0
        let minute = notificationTime["minute"] as? Int ?? 0
        // ... further handling of your data
      }
    }
  }
}

That being said, I'd like to suggest looking into Timestamps for storing date-time related data. See the documentation for more details.

Upvotes: 2

Related Questions