This library helps you to use your custom types that conform to Codable protocol with Firebase. Here's an example of a custom model:
structModel:Codable{enumMyEnum:Int,Codable{case one, two, three
}letstringExample:StringletbooleanExample:BoolletnumberExample:DoubleletdateExample:DateletarrayExample:[String]letoptionalExample:Int?letobjectExample:[String:String]letmyEnumExample:MyEnum}This is how you would use the library with Firebase Realtime Database:
import Firebase
import CodableFirebase
letmodel:Model // here you will create an instance of Model
letdata=try!FirebaseEncoder().encode(model)Database.database().reference().child("model").setValue(data)And here is how you would read the same value from Firebase Realtime Database:
Database.database().reference().child("model").observeSingleEvent(of:.value, with:{ snapshot inguardlet value = snapshot.value else{return}do{letmodel=tryFirebaseDecoder().decode(Model.self, from: value)print(model)}catchlet error{print(error)}})This is how you would encode a model with Firebase Cloud Firestore:
import Firebase
import CodableFirebase
letmodel:Model // here you will create an instance of Model
letdocData=try!FirestoreEncoder().encode(model)Firestore.firestore().collection("data").document("one").setData(docData){ error iniflet error = error {print("Error writing document: \(error)")}else{print("Document successfully written!")}}And this is how you would decode the same model with Firebase Cloud Firestore:
Firestore.firestore().collection("data").document("one").getDocument{ document, error iniflet document = document {letmodel=try!FirestoreDecoder().decode(Model.self, from: document.data())print("Model: \(model)")}else{print("Document does not exist")}}In order to use these types with Cloud Firestore, you need to add the following code somewhere in your app:
extensionDocumentReference:DocumentReferenceType{}extensionGeoPoint:GeoPointType{}extensionFieldValue:FieldValueType{}extensionTimestamp:TimestampType{}and now they become Codable and can be used properly with FirestoreEncoder and FirestoreDecoder.
PLEASE NOTE that as FieldValue is only used to setData() and updateData(), it only adopts the Encodable protocol.
You can use CocoaPods to install CodableFirebase by adding it to your Podfile:
platform :ios, '9.0'
use_frameworks!
target 'MyApp' do
pod 'CodableFirebase'
endNote that this requires CocoaPods version 36, and your iOS deployment target to be at least 9.0:
You can use Carthage to install CodableFirebase by adding it to your Cartfile:
github "alickbass/CodableFirebase"