0

I have this method to extract user data (from Firestore) into a custom UserModel Struct. But, it isn't returning the desired user data out of the function:


    func getArtistProfileCardData(artistName: String) -> UserModel {
        
        var retData: UserModel = UserModel(isArtist: false, first: "", last: "", artistName: "something", occupation: "", profileUrl: "", followers: 0)
        
        let usersRef = db.collection("users")
        usersRef.whereField("artistName", isEqualTo: artistName)
            .getDocuments { (querySnapshot, err) in
                if let err = err {
                            print("Error getting documents: \(err)")
                        } else {
                            for document in querySnapshot!.documents {
                                print("\(document.documentID) => \(document.data())")
                                do {
                                    let data = try document.data(as: UserModel.self)
                                    retData = data
                                    // printing retData.artistName gives me correct output.
                                } catch _ {
                                    print("Error getting document from querySnapshot.")
                                }
                            }
                        }
            }
        // printing retData.artistName gives me "something" which I initialized right in the beginning of this function. 
        return retData
        }

IRC, the innermost closure should capture the retData variable so I should be able to extract the data inside data variable and return it out of the function. However, that isn't what's happening. Why is that so? And how would I go about achieving the desired effect?

Thank you.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • All of those closures execute asynchronously after the network operations are complete. Your `return` doesn't wait for that. It executes immediately. As well as the duplicate you can look at async/await – Paulw11 Jun 17 '22 at 09:50
  • Thank you so much! I followed the links and found some really good resources on Async Code and managed to create my own completionHandler for said task. However, I've hit another roadblock. – Apekshik Panigrahi Jun 17 '22 at 15:03

0 Answers0