cjochum
cjochum

Reputation: 79

How to map fields from Firestore documents in Swift

In my Firestore database, I have "favorites" getting stored like this:

enter image description here

How can I get the values "S1533" and "S2017" based on itemActive = true?

Here is the Swift code I have, but I am stuck on how to look at itemActive and then go back and return the values that have that field as set to true.

db.collection("users").document(userId!).addSnapshotListener { documentSnapshot, error in
        guard let document = documentSnapshot else {
            print("Error fetching document: \(error!)")
            return
        }
        guard let data = document.data() else {
            print("Document data was empty.")
            return
        }
        print(data["favorites"])
    }

Upvotes: 0

Views: 1138

Answers (1)

Peter Friese
Peter Friese

Reputation: 7254

The easiest way to map Firestore documents is to use Codable. This article to learn about the basics.

For your model, the following code should get you started:

Model

struct Favourite: Codable, Identifiable {
  var itemActive: Bool
  var itemAdded: Date
}

struct UserPreference: Codable, Identifiable {
  @DocumentID public var id: String?
  var displayName: String
  var email: String
  var favourites: [Favourite]?
}

Fetching data

public class UserPreferenceRepository: ObservableObject {
  var db = Firestore.fireStore()
  @Published var userPreferences = [UserPreference]()
  private var listenerRegistration: ListenerRegistration?

  public func subscribe() {
    if listenerRegistration == nil {
      
      var query = db.collection("users")
      
      listenerRegistration = 
        query.addSnapshotListener { [weak self] (querySnapshot, error) in
          guard let documents = querySnapshot?.documents else {
            self?.logger.debug("No documents")
            return
          }
          
          self?.userPreferences = documents.compactMap { queryDocumentSnapshot in
            try? queryDocumentSnapshot.data(as: UserPreference.self)
          }
        }
    }
  }

Upvotes: 2

Related Questions