Home > Mobile >  Swift error trying to find document in firebase by id using CODABLE class
Swift error trying to find document in firebase by id using CODABLE class

Time:12-17

I'm trying to find a document using its id and store in a custom data class. So far, I've created my first function to search in Firebase a user by email. Email is the Id of the document. I've created a class as well to store the the user. You can see both codes here: My firebase database: enter image description here My class:

import Foundation
import FirebaseFirestoreSwift


    class Usuario: Codable {
    @DocumentID var email: String?
    let nombre: String
    let apellidos: String
    let telefono: String
    let contraseña: String
    let fotoPerfil: String?
    let ciudad: String
    
        init ( nombre: String, apellidos: String, usuario: String, contraseña: String, fotoPerfil: String?, ciudad: String){
            self.nombre = nombre
            self.apellidos = apellidos
            self.telefono = usuario
            self.contraseña = contraseña
            self.fotoPerfil = nil
            self.ciudad = ciudad
    }

My function:

private func buscarUsuarioPorEmail( documentId: String) {
  let docRef = db.collection("Usuarios").document("[email protected]")
  print("This is a quick check for debugging:  \(documentId)")
  docRef.getDocument(as: Usuario.self) { result in
    switch result {
    case .success(let usuario):
      self.usuarioActual = usuario
        print("El usuario actual es: \(self.usuarioActual.nombre) ")
        print(result)
    case .failure(let error):
      print("ERROR ENCONTRADO USUARIO \(error.localizedDescription)")
    }
  }
}

My main view:

import UIKit
import FirebaseAuth
import FirebaseCore
import FirebaseAnalytics
import FirebaseFirestore
import Lottie

class InicioViewController: UIViewController {
    // He utilizado una variable tipo lazy para poder inicializarla más tarde cuando se llama a la base datos
    lazy var usuarioActual = Usuario()
    lazy var usersCollection = Firestore.firestore().collection("Usuarios")
    @IBOutlet weak var txtEmailUsuario: UITextView!
    // Creamos una conexión a Firestore
    private let db = Firestore.firestore()
    lazy var collectioRef = db.collection("Usuarios")
    
    // MARK: -- Recupero el email mediante su clave en UserDefaults
    private let email = UserDefaults.standard.string(forKey: "emailAutentificado")
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Datos usuario actual"
        txtEmailUsuario.text = email
        buscarUsuarioPorEmail(documentId: email!)
}

I'm allways reciving the same console error:

This is a quick check for debugging: [email protected]
ERROR ENCONTRADO USUARIO The data couldn’t be read because it is missing.

CodePudding user response:

so I think the issue could be this variables in your decodable:

let contraseña: String

Translated It looks like this means password so if you make this nullable, or just remove it, see if it starts working as your document does not contain a value for a key of password.

  • Related