'Fetching data from collection 'profiles' in Cloud Firestore with SwiftUI. Cannot assign value of type '[String : Any]' to type 'UserProfile'

I'm new to developing, looking for some help.

I've managed to create a collection of profiles stored in Cloud Firestore. I now want to retrieve the signed in users profile information to use throughout my app.

Here is what I have so far:

import SwiftUI
import Firebase

class UserViewModel: ObservableObject {
  @Published var user: UserProfile = UserProfile(uid: "", firstName: "", email: "", gender: "")
    
  private var db = Firestore.firestore()

  func fetchProfileFirstName () {
    let userId = Auth.auth().currentUser?.uid ?? "" 
    db.collection("profiles").document(userId)
      .addSnapshotListener { documentSnapshot, error in
      guard let document = documentSnapshot else {
        print("Error fetching document: \(error!)")
        return
      }
      guard let data = document.data() else {
        print("Document data was empty.")
        return
      }
      print("Current data: \(data)")
      self.user = data
    }
  }
}

I'm getting the error: 'Cannot assign value of type '[String : Any]' to type 'UserProfile'

Thanks in advance.



Solution 1:[1]

Firebase supports the Codable API, which enables you to perform type-safe mapping from Firebase documents to Swift structs.

Here's what you need to do to implement it:

  1. Add FirebaseFirestoreSwift to your Podfile
  2. Import FirebaseFirestoreSwift
  3. Make sure your UserProfile struct implements Codable
  4. When reading documents, you can call return try? queryDocumentSnapshot.data(as: UserProfile.self)
  5. When writing documents, call try db.collection("profiles").addDocument(from: userProfile)

I covered this in detail in Mapping Firestore Data in Swift - The Comprehensive Guide, and also recorded this video.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1