How to pull a specific firebase document using Swift?

Asked

Viewed 64 times

0

I’m trying to get a document inside a collection, but I can only get it all at once.

The way in the firebase looks like this: Collection: digital-liquors. Documents: adult(That’s what I’m trying to catch), childish, juvenile.

I’m using the following code:

    func loadLessons() -> Observable<[LessonsModel]> {
        let collection = self.db.collection("licoes-digital")
        return Observable.create { observer in
            collection.getDocuments() { (querySnapshot, err) in
                if let err = err {
                    print("Error: \(err)")
                    observer.onError(err)
                } else {
                    var items : [LessonsModel] = []
                    for document in querySnapshot!.documents {
                        var item = LessonsModel()
                        let data : [String:Any] = document.data()
                        let lessons : Array<[String:Any]> = data["licoes"] as! Array
                        for lesson in lessons {
                            item.cover = lesson["capa"] as! String
                            item.content = lesson["conteudo"] as! String
                            items.append(item)
                    }
                }
                observer.onNext(items)
            }

        }
        return Disposables.create()
    }
}

I think my mistake is on the line :

collection.getDocuments() { (querySnapshot, err) in

I should replace getDocuments() to get just one document, but I don’t know if there is a specific function for it, or I would have to create it. And if it is necessary to create how to create ?

1 answer

0

I believe that to obtain only one document its function to be used would be getDocument, as in the example below:

//substituir 'nome-do-doc' por: adulto,infantil,juvenil
let docRef = db.collection("licoes-digital").document("nome-do-doc") 

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        //transformar no seu objeto
    } else {
        print("Document does not exist")
    }
}

I also recommend avoiding force unwrap. Use nil coalescing and conditional binding is safer and will not crash if some value is not converted successfully. It would look something like this:

var item = LessonsModel()
let data : [String:Any] = document.data()
if let lessons = data["licoes"] as? Array<[String:Any]> {
  for lesson in lessons {
    item.cover = lesson["capa"] as? String ?? ""
    item.content = lesson["conteudo"] as? String ?? ""
    items.append(item)
  } 
}

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.