Passing data from Content Model

This seems like it should be fairly easy, but I am stuck and can’t figure out why…

I am trying to load meta data for someone other than the current user (ie: a friend) and can’t seem to get the data into usable variables.

model:

class User: Identifiable {
var uid = “”
var nickname = “”
}

content model:

import Foundation
import FirebaseFirestore
import FirebaseAuth

class ContentModel: ObservableObject {

let db = Firestore.firestore()

var aUser: User?

func getUserData() {

    let ref = db.collection("users").document("ROkkq5inLJfVF01103FthH9UhNn1")
    ref.getDocument { snapshot, error in
        
        guard error == nil, snapshot != nil else {
            return
        }
        
        let data = snapshot!.data()
        
        // when I simply print the nickname, it works
        print(data?["nickname"] as? String ?? "")
        
        // when I try to put the data into a variable, I get nil
        self.aUser?.nickname = data?["nickname"] as? String ?? ""
        print(self.aUser?.nickname)
    }
}

What am I doing wrong?

@CeilingTiles

Hi Brent,

You have declared aUser as Optional so when you try to assign anything to it you would need to initialise it at that time. ie:

            // when I try to put the data into a variable, I get nil
            //  Initialise it before using it.
            self.aUser = User()
            self.aUser?.nickname = data?["nickname"] as? String ?? ""
            print(self.aUser?.nickname)

The other option is where you declare the variable do it like this:

var aUser = User()

and then down in your Firebase code do this:

            // when I try to put the data into a variable, I get nil

            self.aUser.nickname = data?["nickname"] as? String ?? ""
            print(self.aUser.nickname)
1 Like

Thank you, Chris. Thank you thank you thank you.

You should buy a lottery ticket 'cuz you’ve got tons of good karma.