Firebase is a remote database that can be integrated with Xcode and Swift. It allows the user to save data in the cloud and retrieve it as well.
I started looking into Firebase and there are some things I like and some things I don’t like.
I really like the possibility to look at the database in a visual form and to have the ability to edit entries in the cloud. This is a functionality that I didn’t find when I was using Core Data. I don’t like, that I had to install cocoa pods. It took me a couple of hours because I got error messages. I also dislike that building the project takes a long time, even though I am working with basic projects. In addition to that, I also currently have problems retrieving data
This is what I have been doing so far.
Importing Firebase
If I want to use Firebase in one of my Swift Programs, I have to import Firebase. To achieve that, I need to write:
import Firebase
Initializing Firebase
When I have Firebase imported, I have to call set up Firebase. This is done in the initializing Method of the entry point of the Swift project.
@main struct FirebaseProject: App { init(){ FirebaseApp.configure() } }
Calling methods that use Firebase
When I am done with the first two steps, I can use functions to call, when I want to create data, update data or delete data. Before I can do this, I need a reference to the database. For that, I write:
let db = Firestore.firestore()
When I have access to the database, I need to select a collection. For that, I write:
let collection = db.collection("collectionName")
Now I have access to the collection. With this, I can access the documents that are in this collection. I can also create new documents in the collection.
Create
To create a new document, I can write:
let newDocument = collection.document()
To set the data in the new document, I can write:
newDocument.setData(["key":"value"])
The data is stored in a dictionary with a key value pair. As far as I know, the key has to be a string and the value can have different types, like string, int, boolean and some more.
Update
To update the value of a specific key of a document, I can write:
newDocument.updateData(["key":"updatedValue"])
This will only update the value for the specified key. If the document has a dictionary with more than one key, the other keys will not be affected or changed. If I overwrite the data, like this:
newDocument.setData(["key":"newValue")
All other keys in the dictionary will be gone because this overwrites the entire dictionary of the document.
Delete
If I want to delete this document, I can write:
newDocument.delete()
If I am using a for loop, I need to call the reference on the document, which would look like this:
for document in documents { document.reference.delete() }
Connecting to User Interface
Once Firebase is set up in the @main
structure, I can use it in my views, like the ContentView