Home > Software design >  Assign firestore value to variable using read function in Swift
Assign firestore value to variable using read function in Swift

Time:10-06

I'm reading data from a firestore database in the function below, and I want to assign specific data values to variables in my structure. For example I have the variable 'currentRating' that I want to equal data.currentRating. How would I call the data value in my variable?

    private func listenDocument() {
        Firestore.firestore().collection("RatingInformation").document("Brittain")
            .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("Current data: \(data)")
            }
    }

CodePudding user response:

Here is how you get data by key-value concept:

// Add callback using closure
func fetchRatingInfomation(documentPath: String, completion: ([String: Any]?) -> Void) {
    Firestore.firestore()
        .collection("RatingInformation")
        .document(documentPath)
        .addSnapshotListener { documentSnapshot, error in
            guard let document = documentSnapshot else {
                print("Error fetching document: \(error!)")
                completion(nil)
                return
            }
            guard let jsonData = document.data() else {
                print("Document data was NULL.") //
                completion(nil)
                return
            }
            
            print("Current data: \(jsonData)")
            completion(jsonData)
        }
    }
}

// Calling inside your class body
fetchRatingInfomation(documentPath: "Brittain") {[weak self] jsonData in
    guard let _jsonData = jsonData else { return }
    print(_jsonData["currentRating"]) // Here is how you get value of document's attribute
}

CodePudding user response:

I would make use of the document's get function.

private func listenDocument() {
    Firestore.firestore().collection("RatingInformation").document("Brittain").addSnapshotListener { (snapshot, error) in
        guard let doc = snapshot else {
            if let error = error {
                print("error", error)
            }
            return
        }
        guard doc.exists else {
            print("no document")
            return
        }
        if let currentRating = doc.get("currentRating") as? Int {
            someExistingStruct.currentRating = currentRating
        }
        if let usualRating = doc.get("usualRating") as? Int {
            someExistingStruct.usualRating = usualRating
        }
        if let someTitle = doc.get("someTitle") as? String {
            someExistingStruct.someTitle = someTitle
        }
        // and so on...
    }
}
  • Related