Search code examples
jsonswiftfirebase-realtime-databasejson-deserialization

Can Swift 4's JSONDecoder be used with Firebase Realtime Database?


I am trying to decode data from a Firebase DataSnapshot so that it can be decoded using JSONDecoder.

I can decode this data fine when I use a URL to access it with a network request (obtaining a Data object).

However, I want to use the Firebase API to directly obtain the data, using observeSingleEvent as described on this page.

But, when I do this, I cannot seem to convert the result into a Data object, which I need to use JSONDecoder.

Is it possible to do the new style of JSON decoding with a DataSnapshot? How is it possible? I can't seem to figure it out.


Solution

  • I have created a library called CodableFirebase that provides Encoders and Decoders that are designed specifically for Firebase.

    So for the example above:

    import Firebase
    import CodableFirebase
    
    let item: GroceryItem = // here you will create an instance of GroceryItem
    let data = try! FirebaseEncoder().encode(item)
    
    Database.database().reference().child("pathToGraceryItem").setValue(data)
    

    And here's how you will read the same data:

    Database.database().reference().child("pathToGraceryItem").observeSingleEvent(of: .value, with: { (snapshot) in
        guard let value = snapshot.value else { return }
        do {
            let item = try FirebaseDecoder().decode(GroceryItem.self, from: value)
            print(item)
        } catch let error {
            print(error)
        }
    })