Happy Sunday everyone. I have a problem with decoding my data. I can't seem to decode data from when I serialize dictionary strings into an object. Im trying to fetch matches from firebase, and this works for when I fetch user profiles but not with fetching matches.
func fetchMatches(onCompletion: @escaping (Result<[MatchModel], DomainError>) -> ()){
db.collection("matches").whereField("usersMatched", arrayContains: userId!).getDocuments(completion: {doc, err in
guard let documentSnapshot = doc, err == nil else{
onCompletion(.failure(.downloadError))
return
}
var matchList: [MatchModel] = []
var count = 0
let maxCount = documentSnapshot.documents.count
var hasFailed = false
for document in documentSnapshot.documents{
if hasFailed{ break }
let decoder = JSONDecoder()
var dict = document.data()
for (key, value) in dict {
if let value = value as? Timestamp {
let formatter = DateFormatter()
let newValue = value.dateValue()
formatter.dateStyle = .short
formatter.timeStyle = .none
dict[key] = formatter.string(from: newValue)
}
}
Up until here I know that everything is going well. Dict contains -
Dictionary
["timestamp": "10/22/22", "usersMatched": <__NSArrayM 0x600002c61680>(
6euZHDmI7PMDcCmft5MfxUW27jI3,
tbcB0ay0YEgZcY9UsZ00WjZ9h893
)
]
data below prints out 105 bytes, so with that information I know that it isn't empty and that JSONSerialization did its job of converting dict into an object. But then when I try to decode it into FirestoreMatch.self match returns empty
if let data = try? JSONSerialization.data(withJSONObject: dict, options:[]){
do{
let match = try? decoder.decode(FirestoreMatch.self, from: data)
let matchId : String = match!.usersMatched.filter{$0 != self.userId!}.first!
... }
catch{
print(error)
Error returns:
typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "timestamp", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))
This is my FirestoreMatch struct
struct FirestoreMatch: Codable{
let usersMatched: [String]
let timestamp: Date
}
Do I require more information for my struct? Im not sure why match returns nil