Fovvu
Fovvu

Reputation: 133

Need acces from document to collection Firestore

I'm trying to do an iOS app and i've binded it with firebase, so I'm trying to get some posts ad fetch them, and this works fine, however this posts got 2 collections (likes and replies) and i'm trying to fetch likes, the thing is that I can't get the likes because for some reasons I can't a class for document forEach neither I can't access it, someone got any idea?

Code:

import Foundation
import Firebase

struct Post : Hashable {
    var id : String
    var dateAdded : String
    var posterEmail : String
    var posterUsername : String
    var posterIcon : String
    var postTitle : String
    var postBody : String
    var likes : [String]
    var userLikedPost : Bool
}

struct Like {
    var likeId : String
    var likerEmail : String
}

class Likes {
    var likes : [Like] = []
    
    func fetchLikes() {
        //Firestore.firestore()
    }
}


class Posts : ObservableObject {
    @Published var posts : [Post] = []
    
    func fetchPosts() {
        Firestore.firestore().collection("posts").getDocuments(completion: { (docPosts, error) in
            if (error != nil) {
                print("error fetching posts")
            } else {
                docPosts?.documents.forEach { (post) in
                    let id = post.documentID
                    let email = post.get("posterEmail") as! String
                    let username = post.get("posterUsername") as! String
                    let icon = post.get("posterIcon") as! String
                    let title = post.get("title") as! String
                    let body = post.get("body") as! String

                    // Here i want to insert the code that gets the likes class and access the likes variable
                    
                    self.posts.append(Post(id: id, dateAdded:String(id.split(separator: "_").joined(separator: "/").prefix(10)) ,posterEmail: email, posterUsername: username, posterIcon: icon, postTitle: title, postBody: body,
                                           likes: [],userLikedPost: false))
                }
            }
        })
    }
}

Upvotes: 1

Views: 59

Answers (1)

Jay
Jay

Reputation: 35677

The Firestore structure was not included in the question so I will present one for use

user_wines
   uid_0
      name: "Jay"
      favorite_wines:
         0: "Insignia"
         1: "Scavino Bricco Barolo"
         2: "Lynch Bages"
   uid_1
      name: "Cindy"
      favorite_wines
         0: "Palermo"
         1: "Mercury Head"
         2: "Scarecrow"

And then the code to read all of the user documents, get the name, the wine list (as an array as Strings) and output it to console

func readArrayOfStrings() {
    let usersCollection = self.db.collection("user_wines")
    usersCollection.getDocuments(completion: { snapshot, error in

        guard let allDocs = snapshot?.documents else { return }

        for doc in allDocs {
            let name = doc.get("name") as? String ?? "No Name"
            let wines = doc.get("favorite_wines") as? [String] ?? []
            wines.forEach { print("   ", $0) }
        }

    })
}

and the output

Jay
   Insignia
   Scavino Bricco Barolo
   Lynch Bages
Cindy
   Palermo
   Mercury Head
   Scarecrow

EDIT

Here's the same code using Codable

class UserWineClass: Codable {
   @DocumentID var id: String?
   var name: String
   var favorite_wines: [String]
}

and the code to read data into the class

for doc in allDocs {
    do {
        let userWine = try doc.data(as: UserWineClass.self)
        print(userWine.name)
        userWine.favorite_wines.forEach { print("   ", $0) }
    } catch {
        print(error)
    }
}

Upvotes: 1

Related Questions