Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 589
wazawoo Avatar asked Nov 23 '17 23:11

wazawoo


People also ask

Which is faster firestore or Realtime Database?

Cloud Firestore also features richer, faster queries and scales further than the Realtime Database.

Which query language is used in Firebase?

Firebase uses NoSQL; MySQL uses SQL.

How much traffic can Firebase handle?

The limit you're referring to is the limit for the number of concurrently connected users to Firebase Realtime Database on the free Spark plan. Once you upgrade to a payment plan, your project will allow 200,000 simultaneously connected users.

Can I use both Realtime Database and firestore?

You can use both Firebase Realtime Database and Cloud Firestore in your app, and leverage each database solution's benefits to fit your needs. For example, you might want to leverage Realtime Database's support for presence, as outlined in Build Presence in Cloud Firestore.


1 Answers

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)
    }
})
like image 80
Noobass Avatar answered Oct 04 '22 12:10

Noobass