Home > Mobile >  Keep getting `FIRInvalidArgumentException` when attempting to Encode() in swift
Keep getting `FIRInvalidArgumentException` when attempting to Encode() in swift

Time:07-15

I am trying to pass a simple struct with string values to Firestore but I keep getting FIRInvalidArgumentException even though I made my struct Codable. Here is my code:

public struct Device: Codable {
    let name: String?
    let address: String?
    let serialNum: String?
    let email: String?
    let password: String?
}

func bindDeviceToUser(name: String?, email: String, devicePassword: String?, serialNum: String?, address: String?) {

    let device = Device(name: name, address: address, serialNum: serialNum, email: email, password: devicePassword)

    if let data = try? Firestore.Encoder().encode(device) {
        firestore.collection("Users").document(email).collection("Devices").document(serialNum!).setData(["Data" : data])
    }
}

Why am I still getting this error? Am I using Firestore.Encoder() wrong?

CodePudding user response:

Yes, you're using Encoder "incorrectly" e.g. you don't need it.

Try this

Here's the model. Set it up as Codable with a @DocumentID which you will need later to update that model:

struct Device: Codable {
    @DocumentID var id: String?
    var name: String
    var address: String
    var serialNum: String
    var email: String
    var password: String
}

and then writing or updating the model

func updateDevice(aDevice: Device) {
  if let docId = aDevice.id {
    let docRef = db.collection("Devices").document(docId)
    do {
      try docRef.setData(from: aDevice)
    } catch {
      print(error)
    }
  }
}

and to read it

func fetchDevice(docId: String) {
  let docRef = db.collection("Devices").document(docId)
  
  docRef.getDocument(as: Device.self) { result in
    switch result {
    case .success(let device):
      // do something with the device
    case .failure(let error):
      print(error.localizedDescription)
    }
  }
}

I will point you to this outstanding blog by Peter Friese on how to use Codable with Firestore

Mapping Firestore Data in Swift

  • Related