ios – How to get custom model from Firestore data in Swift


import Firebase
import FirebaseFirestoreSwift

struct UserProfileModel: Identifiable, Decodable {
    @DocumentID var id: String?
    let username: String
    let fullname: String
    let profileImageUrl: String
    let email: String
}


struct UserService {
    
    func fetchUser(withUid uid: String) {
        print("DEBUG: Fetch user info")
//        print("DEBUG: User info og uid \(uid)")
        Firestore.firestore().collection("users").document(uid).getDocument { snapshot, error in
            guard let snapshot = snapshot?.data()
            else {
                print("user not printed")
                return
            }
            print("DEBUG: User data is \(snapshot)")
            
            guard let user = try? snapshot.data(as: UserProfileModel.self)
            else {
                print("user not printed \(error?.localizedDescription)")
                return
            }
            print("DEBUG: Username is \(user.username)")
            print("DEBUG: Email is \(user.email)")
        }
    }
}
guard let snapshot = snapshot?.data() 

In snapshot I will get current user data.

but in this line

guard let user = try? snapshot.data(as: UserProfileModel.self)

when I print this user then null print ho Raha ha
but I want same snapshot data as a UserProfileModel object

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img