<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kyle Beard on Medium]]></title>
        <description><![CDATA[Stories by Kyle Beard on Medium]]></description>
        <link>https://medium.com/@kylebeard?source=rss-aed10931f645------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F2tnnqaDpwf-eroIFpJT2A@2x.jpeg</url>
            <title>Stories by Kyle Beard on Medium</title>
            <link>https://medium.com/@kylebeard?source=rss-aed10931f645------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 04:50:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kylebeard/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Realm to cache with Firebase]]></title>
            <link>https://kylebeard.medium.com/using-realm-to-cache-with-firebase-617f7488380e?source=rss-aed10931f645------2</link>
            <guid isPermaLink="false">https://medium.com/p/617f7488380e</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[realm]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Kyle Beard]]></dc:creator>
            <pubDate>Sun, 15 Dec 2024 18:42:55 GMT</pubDate>
            <atom:updated>2024-12-15T18:53:55.772Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this tutorial, we’ll implement a caching strategy to cut down on over-querying fresh data from Firebase.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZqYRoA4Rg7YHllBBGuzww.png" /><figcaption>Firebase x Swift by <a href="https://kylebeard.medium.com/">Kyle Beard</a></figcaption></figure><p><strong>Missed Part 1?</strong> Check out <a href="https://betterprogramming.pub/getting-started-with-firebase-using-generics-ec7e04123c83">Getting Started With Firebase Using Generics in Swift</a> to get familiar!</p><p>In my previous article, I explored how to integrate a lightweight API layer into your iOS app using Firebase’s Cloud Firestore. While Firebase offers exceptional convenience, challenges can arise as your app scales. Unexpectedly high read operations can quickly push you beyond Firebase’s free Spark plan limit of 50k reads per day, leading to mounting monthly costs.</p><p>But cost isn’t the only concern. Relying heavily on network calls to fetch data can slow down your app and degrade the user experience, especially in areas with poor connectivity. Even with strategies like pagination or lazy loading, scaling without a robust local caching solution can lead to both financial strain and performance bottlenecks.</p><p>So, how can we address these issues? Enter Realm — a MongoDB product that not only simplifies reading and writing data directly to your user’s local device but also helps reduce network dependency. By caching data locally, Realm allows your app to perform faster, even offline, while cutting down on API costs by minimizing the number of read operations.</p><h4>Disclaimer</h4><p>This tutorial is using Realm only as an offline caching mechanism since Atlas Device Sync functionality was deprecated in September 2024.</p><h3>1. Understanding our caching goals</h3><h4>Why use caching?</h4><p>Before implementing caching, every time your app needed data, you would just call the API directly. This approach ensured two critical things: 1) the data retrieved was always from a single source of truth, and 2) it was the most up-to-date information available. When introducing a caching layer, it’s important that we must maintain these two principles to avoid the risk of delivering outdated or incorrect data, which could lead to a poor user experience.</p><p>While this may seem like a simple concept, you might find that thinking through the design and implementation could be somewhat of a Catch-22. How can you for sure know the data you’re seeking is fresh <em>without </em>explicitly checking it beforehand? Well, by implementing timestamp-based tracking, you can make decisions within your app service for whether to retrieve data from remote (API), local (cache), or a combination of both.</p><h4>What will it looks like?</h4><p>Let’s consider a real-world example using our library of books to outline a simple caching strategy before diving into the code:</p><ol><li>As a new user, my device starts with an empty cache. When I query the list of available books at my local library, the app makes a call to the API. At this point, I store the current <strong>Unix timestamp</strong> (a numerical representing the time the query was made). This timestamp serves as a reference point for distinguishing between past and future data.</li><li>To ensure data freshness between the client and server, we’ll modify our database models to include a new field called lastUpdatedAt, which stores a Unix timestamp. Whenever data is written back to the API, this field will be updated to reflect the current time.</li><li>In the future, when I query the API for the list of books again, we can use a Firebase query to retrieve only the records where the lastUpdatedAt value is <em>greater than</em> the timestamp from the previous query. This approach ensures we only load freshly updated data from the server, while leveraging the cached data for anything that hasn’t changed. This way, we maintain a seamless balance between up-to-date information and efficient data reuse.</li></ol><h3>2. Prepare codebase for caching</h3><h4>Update our models</h4><p>Now that we’ve outlined our approach, let’s modify our code from our previous article to be cache-friendly. First, let’s update our model to include the new lastUpdatedAt field:</p><pre>struct Book: FirebaseIdentifiable {<br>    var id: String<br>    var libraryID: String<br>    var name: String<br>    var author: String<br>    var pages: Int<br>    var isCheckedOut: Bool<br>    var lastUpdatedAt: Double<br><br>    init(<br>        id: String = UUID().uuidString,<br>        libraryID: String = &quot;&quot;,<br>        name: String = &quot;&quot;,<br>        author: String = &quot;&quot;,<br>        pages: Int = 0,<br>        isCheckedOut: Bool = false,<br>        lastUpdatedAt: Double = 0.0<br>    ) {<br>        self.id = id<br>        self.libraryID = libraryID<br>        self.name = name<br>        self.author = author<br>        self.pages = pages<br>        self.isCheckedOut = isCheckedOut<br>        self.lastUpdatedAt = lastUpdatedAt<br>    }<br>}</pre><h4>Setting up Realm</h4><p>Next, let’s setup our Realm service and make sure that we have our pre-requisite Firebase queries ready to go! I used Swift Package Manager to install <a href="https://github.com/realm/realm-swift">RealmSwift</a>. Then, I setup a basic class that will allow me to cache specific data by collection.</p><pre>import RealmSwift<br>import SwiftUI<br><br>@MainActor class RealmService: ObservableObject {<br>    static let shared = RealmService()<br>    init() { print(&quot;init RealmService&quot;) }<br>    deinit { print(&quot;deinit RealmService&quot;) }<br>}<br><br>class RealmCache: Object {<br>    @Persisted(primaryKey: true) var id: String<br>    @Persisted var data: String = &quot;&quot;<br>    @Persisted var collection: String = &quot;&quot;<br>    <br>    convenience init(id: String, data: String, collection: String) {<br>        self.init()<br>        self.id = id<br>        self.data = data<br>        self.collection = collection<br>    }<br>}<br><br>extension RealmService {<br>    <br>    // MARK: - READ<br>    <br>    func read&lt;T: FirebaseIdentifiable&gt;(of type: T, with id: String) async -&gt; T? {<br>        if let realm = try? await Realm() {<br>            return realm.objects(RealmCache.self).where {<br>                $0.id == id<br>            }.compactMap {<br>                $0.data.decoded()<br>            }.first<br>        } else {<br>            print(&quot;\(#function) realm missing&quot;)<br>            return nil<br>        }<br>    }<br>    <br>    func read&lt;T: FirebaseIdentifiable&gt;(of type: T, in collection: String) async -&gt; [T] {<br>        if let realm = try? await Realm() {<br>            return realm.objects(RealmCache.self).where {<br>                $0.collection == collection<br>            }.compactMap {<br>                $0.data.decoded()<br>            }<br>        } else {<br>            print(&quot;\(#function) realm missing&quot;)<br>            return []<br>        }<br>    }<br>    <br>    // MARK: - WRITE<br>    <br>    func write&lt;T: FirebaseIdentifiable&gt;(_ value: T, to collection: String) async {<br>        if let realm = try? await Realm() {<br>            if let data = value.encoded {<br>                if let realmObject = realm.objects(RealmCache.self).first(where: { $0.id == value.id }) {<br>                    /// UPDATE<br>                    do {<br>                        try realm.write {<br>                            realmObject.data = data<br>                        }<br>                    } catch let error {<br>                        print(&quot;\(#function) update failed, \(error)&quot;)<br>                    }<br>                } else {<br>                    /// CREATE<br>                    let realmObject = RealmCache(id: value.id, data: data, collection: collection)<br>                    do {<br>                        try realm.write {<br>                            realm.add(realmObject)<br>                        }<br>                    } catch let error {<br>                        print(&quot;\(#function) create failed, \(error)&quot;)<br>                    }<br>                }<br>            } else {<br>                print(&quot;\(#function) encoding to JSON failed&quot;)<br>            }<br>        } else {<br>            print(&quot;\(#function) realm missing&quot;)<br>        }<br>    }<br><br>   // MARK: - DELETE<br>    <br>    func delete&lt;T: FirebaseIdentifiable&gt;(_ value: T) async {<br>        if let realm = try? await Realm() {<br>            if let realmCache = realm.objects(RealmCache.self).first(where: { $0.id == value.id }) {<br>                realm.delete(realmCache)<br>            }<br>        } else {<br>            print(&quot;\(#function) realm missing&quot;)<br>        }<br>    }<br>    <br>    func nuke() async {<br>        if let realm = try? await Realm() {<br>            realm.deleteAll()<br>        } else {<br>            print(&quot;\(#function) realm missing&quot;)<br>        }<br>    }<br>}</pre><p>By extending RealmService, I’m able to implement the generic read, write, and delete functions as specified from the Realm SDK, which is well documented if you’re curious how it’s structured.</p><h4>Housekeeping extensions</h4><p>To tie a bow on setting up our project for caching, a few extensions for needing to be written to assist. First, I wrote a wrapper for Firebase’s Query class that allows you to pass conditionals for whether a query should be applied since it relies on method chaining. Next, I added additional conformance for Codable to both FirebaseIdentifiable as the encoder and String as the decoder.</p><pre>import Firebase<br>import FirebaseAuth<br>import FirebaseFirestoreSwift<br>import Foundation<br><br>extension Query {<br>    func whereField(useCondition: Bool, _ field: String, isGreaterThan: Any) -&gt; Query {<br>        if useCondition {<br>            return self.whereField(field, isGreaterThan: isGreaterThan)<br>        } else {<br>            return self<br>        }<br>    }<br>}<br><br>extension FirebaseIdentifiable {<br>    var encoded: String? {<br>        if let data = try? JSONEncoder().encode(self), let string = String(data: data, encoding: .utf8) {<br>            return string<br>        } else {<br>            return nil<br>        }<br>    }<br>}<br><br>extension String {<br>    func decoded&lt;T: FirebaseIdentifiable&gt;() -&gt; T? {<br>        if let data = self.data(using: .utf8), let obj = try? JSONDecoder().decode(T.self, from: data) {<br>            return obj<br>        } else {<br>            return nil<br>        }<br>    }<br>}</pre><h3>3. Add caching logic</h3><h4>Caching a single book</h4><p>Next, we can update our API layer for the singular GET request to handle fetching from cache:</p><pre>struct BookService {<br>    static func getBook(by id: String, useCache: Bool = true) async -&gt; Result&lt;Book, Error&gt; {<br>        <br>        // 1.<br>        let now: String = String(Date().timeIntervalSince1970)<br>        let key: String = &quot;cache/books/\(id)&quot;<br>        let lastQueriedAt = UserDefaults.standard.string(forKey: key)<br>        let lastQueriedTimestamp: Double = Double(lastQueriedAt ?? &quot;&quot;) ?? 0.0<br><br>        do {<br>            // 2.<br>            let query = FirebaseService.shared.database<br>                .collection(&quot;books&quot;)<br>                .whereField(&quot;id&quot;, isEqualTo: id)<br>                .whereField(useCondition: useCache, &quot;lastUpdatedAt&quot;, isGreaterThan: lastQueriedTimestamp)<br>            <br>            // 3.<br>            let books = try await FirebaseService.shared.getOne(of: Book(), with: query).get()<br>            <br>            // 4.<br>            await RealmService.shared.write(data, to: &quot;books&quot;)<br>            UserDefaults.standard.set(now, forKey: key)<br><br>            return .success(books)<br>        } catch let error {<br>            if let error, error == .documentNotFound, useCache {<br>                // 5.<br>                if let data = await RealmService.shared.read(of: Book(), with: id) {<br>                    return .success(data)<br>                } else {<br>                    // 6.<br>                    return await getBook(by: id, useCache: false)<br>                }<br>            } else {<br>                return .failure(error)<br>            }<br>        }<br>    }<br>}</pre><ol><li>At the time of the query, record the current Unix timestamp and define a unique string key for storing this timestamp. Then, retrieve the previously stored timestamp for this specific query if it exists.</li><li>Next, build a Firebase query that fetches a book from the collection only if it matches the given ID and has a lastUpdatedAt value greater than the previously recorded timestamp.</li><li>When calling getOne() from our service, it will either a) return a book, indicating that a newer version of the model exists remotely, or b) return nothing, meaning the book is either already cached (see #5) or it doesn’t exist at all.</li><li>If the service returns a book, update the cache with the new model and write the current timestamp to user defaults to reflect that the cache has been refreshed.</li><li>If an error occurs, first determine if it’s a “document not found” case from Firebase while using the cache. If so, check if the latest model already exists in the cache. If it does, return it. Otherwise, call the function again recursively, this time ignoring the cache by setting the useCache flag to false, ensuring a fresh query against the remote collection without relying on timestamps.</li><li>For any other errors — or errors that occur when the cache is already being ignored — handle them as appropriate, since it indicates the document cannot be retrieved at this time.</li></ol><p>Although this implementation involves multiple steps, these protections create a flexible, resilient architecture suited for a variety of application needs.</p><h4>Querying books in batches</h4><p>Now, let’s consider how this caching mechanism would look for the more popular use-case of batching queries:</p><pre>struct BookService {<br>    static func getBooks(useCache: Bool = true) async -&gt; Result&lt;[Book], Error&gt; {<br>        <br>        let now: String = String(Date().timeIntervalSince1970)<br>        <br>        // 1.<br>        let key: String = &quot;cache/books/all&quot;<br>        let lastQueriedAt = UserDefaults.standard.string(forKey: key)<br>        let lastQueriedTimestamp: Double = Double(lastQueriedAt ?? &quot;&quot;) ?? 0.0<br>        <br>        do {<br>            let query = FirebaseService.shared.database<br>                .collection(&quot;books&quot;)<br>                .whereField(useCondition: useCache, &quot;lastUpdatedAt&quot;, isGreaterThan: lastQueriedTimestamp)<br>            <br>            // 2.<br>            let data = try await FirebaseService.shared.getMany(of: Book(), with: query).get()<br>            <br>            // 3.<br>            let cache = await RealmService.shared.read(of: Book(), in: &quot;books&quot;)<br>        <br>            // 4.<br>            let books = (data + cache).sorted(by: { $0.lastUpdatedAt &gt; $1.lastUpdatedAt })<br>            <br>            // 5.<br>            for d in data {<br>                await RealmService.shared.write(d, to: &quot;books&quot;)<br>                UserDefaults.standard.set(now, forKey: &quot;cache/books/\(id)&quot;)<br>            }<br>        <br>            // 6.<br>            UserDefaults.standard.set(now, forKey: key)<br>        <br>            return .success(books)<br>        } catch let error {<br>            return .failure(error)<br>        }<br>    }<br>}</pre><ol><li>For batching, rather than using the book’s ID to form our unique timestamp key, we use a more general key like /all. In the future, this could be expanded further to handle custom use-cases.</li><li>First, we run a query similar to an individual GET call, but now use getMany() to retrieve as many records as fit our criteria.</li><li>Then, we fetch all previously cached book entries from Realm. This gives us two data sets: the newly fetched data and the existing cache. We then merge them into a single array, sorting by their latest updates.</li><li>Next, we merge our newly fetched data and existing cache into one array and sort by latest update.</li><li>To maintain consistency, any data returned from the API is written back to our cache. After writing to Realm, we also update the corresponding user default, just like we do with individual queries — following the cache/books/id naming convention for timestamps for each book.</li><li>Finally, we update the user default responsible for storing the timestamp associated with the batch query itself.</li></ol><p>Since the service layer handles these operations seamlessly, whenever we call BookService.getBooks(), we can be confident we’re getting the latest data, combining both cached and freshly fetched information.</p><h4>Updating time on writes</h4><p>Lastly, don’t forget to ensure that each time you write models subjected to caching back to the database to update the lastUpdatedAt value. One quick way would be to update immediately upon PUT:</p><pre>extension Book {    <br>    func update() async -&gt; Result&lt;Post, Error&gt; {<br>        var book = self<br>        book.lastUpdatedAt = Date().timeIntervalSince1970<br>        return await FirebaseService.shared.put(book, to: &quot;books&quot;)<br>    }<br>}</pre><h3>4. Understanding expectations and drawbacks</h3><p>While this caching strategy may seem robust, there’s inherent complexity in ensuring that our two main priorities — maintaining a single source of truth (the remote data) and providing the most up-to-date information — are consistently met.</p><h4>Managing deletions</h4><p>One critical challenge is handling data deletions on the remote end. Our timestamp-based approach relies on the idea that models evolve chronologically. If an item is retrieved, stored in cache, and subsequently deleted from the remote source, the cached version remains, now outdated and misleading. This breaks the single source of truth since our local cache appears current, but in reality, it no longer reflects the true state of the remote data.</p><p>A potential workaround, while not perfect, is to “soft delete” records in the remote database rather than removing them entirely. By marking a record as deleted — perhaps through an isDeleted field—your queries can filter out deleted data, enabling the client to recognize these changes and update the cache accordingly.</p><h4>Corrections and database rollbacks</h4><p>Errors and misconfigurations are inevitable in software. In the event of a rollback that restores the database to a previous state, your cached data might become more recent than what now exists remotely. For example, if updates occurred after a backup but before the rollback, the remote data moves back in time while the cached data remains out of sync.</p><p>Such scenarios can create conflicts with maintaining a single source of truth. Without a robust reconciliation strategy, the client may mistakenly believe it holds the newest data, even though the source has reverted to an earlier version.</p><p>If you anticipate database rollbacks in your app’s future, consider implementing a remote configuration setting to trigger a full client-side cache refresh post-rollback — another powerful reason to set useCache = false. This ensures your app fetches the most accurate and current data directly from the source.</p><h3>Wrap Up</h3><p>Woo! We did it again! Or maybe we didn’t and you scrolled to the bottom of my first article, jumped to this article, then scrolled down again looking for these golden words… <a href="https://github.com/kylebeard56/realm-firebase-cache">GitHub</a> project :)</p><p>Thanks for reading again, this was my second article on Medium! I hope you learned something new and consider this architecture in your next iOS project. All feedback is welcome.</p><p>In future articles, I may show you an expanded solution for implementing cache for more data types, such as using Firebase Storage + Realm to manage and cache images.</p><p>In the meantime, check out my products with <a href="https://tigermindlabs.com/">Tiger Mind Labs</a>, or you can find me on: <a href="https://twitter.com/kylebeard_">Twitter</a>, <a href="https://medium.com/linkedin.com/in/kgbeard">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=617f7488380e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With Firebase Using Generics in Swift]]></title>
            <link>https://medium.com/better-programming/getting-started-with-firebase-using-generics-ec7e04123c83?source=rss-aed10931f645------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec7e04123c83</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[generics]]></category>
            <dc:creator><![CDATA[Kyle Beard]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 04:05:26 GMT</pubDate>
            <atom:updated>2024-12-15T18:46:12.915Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this tutorial, we’ll architect a lightweight network layer that makes reading and writing data delightfully simple throughout your app.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUDwlxyZ-g2taEHMK5ofhw.png" /><figcaption><strong>Firebase x Swift</strong> by <a href="http://kylebeard.medium.com/">Kyle Beard</a></figcaption></figure><p>How nice would it be to have one-liner API calls?</p><p>We all know the power of the Google Firebase suite, particularly Cloud Firestore.</p><p>It’s a NoSQL database comprised of collections that contain groups of documents. It’s relatively simple to integrate into your app and before you know it, you’re reading and writing data.</p><p>Yet, because it’s so simple, you can often stray down the dangerous path of writing low-complexity boilerplate code for your network layer. We’ve all been there… too much lazy copypasta, not enough love and care. We can fix that once and for all with Generics. Let’s check it out!</p><h4>Disclaimer</h4><p>For the purposes of this article, the following assumptions are in place:</p><ol><li>You’ve chosen <strong>Cloud Firestore</strong> as your database (although similar tactics can apply to Realtime Database)</li><li>You’re familiar with or using async/await with iOS 15 or newer</li><li>You’ve created your Firebase project in the console</li><li>You’ve generated and imported the GoogleService-Info.plist in Xcode</li><li>You’ve added Firebase and FirebaseFirestoreSwift through some dependency manager (SPM, CocoaPods, etc…)</li><li>You’ve configured Firebase within your AppDelegate</li></ol><h3>1. Setup the service</h3><p>The first thing I do is create the service class for Firebase. This class is fairly light in this case — it’s purely a foundation point for expansion should I bring in any other Firebase products, like Auth or Storage. I went ahead and created an enum for my Collections to help with readability and API versioning, too.</p><p>For this tutorial, my example is building an app for local libraries that want to manage their books and library cards.</p><pre>import Firebase<br>import FirebaseFirestoreSwift<br>import Foundation<br>import SwiftUI<br><br>class FirebaseService {<br>    static let shared = FirebaseService()<br>    let database = Firestore.firestore()<br>    <br>    init() {<br>        // Optional: Tweak the settings below to your app&#39;s needs.<br>        let settings = FirestoreSettings()<br>        settings.isPersistenceEnabled = true<br>        settings.cacheSizeBytes = FirestoreCacheSizeUnlimited<br>        database.settings = settings<br>    }<br>}<br><br>enum Collections: String {<br>    case books = &quot;books-v1&quot;<br>    case cards = &quot;cards-v1&quot;<br>    case library = &quot;library-v1&quot;<br>}</pre><blockquote><strong>Recommendation:</strong> Get into the habit of setting up a separate service class for every third-party integration you pull in, regardless of their overlapping functionalities. This allows you to decouple your codebase to scale fast when platforms or SDKs change i.e. migrating your database from Firebase to AWS or MongoDB without littering your service layer in the refactor.</blockquote><h3>2. Writing the Generic functions</h3><h4>GET Functions</h4><p>Now that our service is setup, we can focus on our next task - <strong>requesting data from Firestore</strong>. Due to the structure of the SDK calls, I created two separate functions for single vs. batched requests.</p><p>For a single request, we can structure our Generic function as such:</p><pre>extension FirebaseService {<br>    // 1.<br>    func getOne&lt;T: Decodable&gt;(of type: T, with query: Query) async -&gt; Result&lt;T, Error&gt; {<br>        do {<br>            // 2.<br>            let querySnapshot = try await query.getDocuments()<br>            if let document = querySnapshot.documents.first {<br>                // 3.<br>                let data = try document.data(as: T.self)<br>                return .success(data)<br>            } else {<br>                print(&quot;Warning: \(#function) document not found&quot;)<br>                return .failure(TutorialError.documentNotFound)<br>            }<br>        } catch let error {<br>            print(&quot;Error: \(#function) couldn&#39;t access snapshot, \(error)&quot;)<br>            return .failure(error)<br>        }<br>    }<br>}</pre><ol><li>This function takes two inputs, one being the type (<em>sigh</em> with Generics not being inferred unless you pass this in — suggestions welcome!) and another being any Firebase queries you’d like to apply that allow you to fetch your data of interest. Because we’ll attempt to decode our data to our object, we’ll want our Generic to conform to Decodable.</li><li>We utilize the Firebase SDK to get the documents in the collection and then because this is a single GET request, we can merely get the first document (assuming your Query is specific enough that one only document will be returned i.e. fetching by primary key).</li><li>Should the document exist, we can decode it from data as such and return it in our Result. Otherwise, we can catch any errors and handle them appropriately here.</li></ol><p>Similarly, we can write another function for getting the batched results and add it into our FirebaseService extension.</p><pre>func getMany&lt;T: Decodable&gt;(of type: T,with query: Query) async -&gt; Result&lt;[T], Error&gt; {<br>    do {<br>        // 1.<br>        var response: [T] = []<br>        let querySnapshot = try await query.getDocuments()<br>        <br>        for document in querySnapshot.documents {<br>            do {<br>                // 2. <br>                let data = try document.data(as: T.self)<br>                response.append(data)<br>            } catch let error {<br>                print(&quot;Error: \(#function) document(s) not decoded from data, \(error)&quot;)<br>                return .failure(error)<br>            }<br>        }<br>        // 3.<br>        return .success(response)<br>    } catch let error {<br>        print(&quot;Error: couldn&#39;t access snapshot, \(error)&quot;)<br>        return .failure(error)<br>    }<br>}</pre><ol><li>Unlike our single request, we’ll want to initialize a list of objects to return in our response.</li><li>Within our for-loop, we can perform similar decoding, but then append it to our list. Any errors are caught here and immediately return failure, regardless of how far we went through our for-loop. An alternative could be to simply log the error, but continue with the loop without returning the failure.</li><li>Once the for-loop is complete, we return our list!</li></ol><h4>Getting ready to write</h4><p>With our GET functions, we were able to make sure we could retrieve the data using Generics by conforming to the Decodable protocol. However, for writing, we need something else that gives us flexibility as we scale our app. Enter FirebaseIdentifiable — the most bare bones protocol ever!</p><p>Since every document in our database will have a unique identifier, and every document will be named after it’s ID, this is a simply architecture decision. We also have some handy tricks we can use it for later that make our writing notation super easy to Firestore (!!).</p><pre>protocol FirebaseIdentifiable: Hashable, Codable {<br>    var id: String { get set }<br>}</pre><h4>POST and PUT Functions</h4><p>One we can read, we must write. POST and PUT are extremely similar with only minute differences being in how we call the document() function.</p><pre>// 1.<br>func post&lt;T: FirebaseIdentifiable&gt;(_ value: T, to collection: String) async -&gt; Result&lt;T, Error&gt; {<br>    // 2.<br>    let ref = database.collection(collection).document()<br>    var valueToWrite: T = value<br>    valueToWrite.id = ref.documentID<br>    do {<br>        //3.<br>        try ref.setData(from: valueToWrite)<br>        return .success(valueToWrite)<br>    } catch let error {<br>        print(&quot;Error: \(#function) in collection: \(collection), \(error)&quot;)<br>        return .failure(error)<br>    }<br>}<br><br>func put&lt;T: FirebaseIdentifiable&gt;(_ value: T, to collection: String) async -&gt; Result&lt;T, Error&gt; {<br>    // 4.<br>    let ref = database.collection(collection).document(value.id)<br>    do {<br>        try ref.setData(from: value)<br>        return .success(value)<br>    } catch let error {<br>        print(&quot;Error: \(#function) in \(collection) for id: \(value.id), \(error)&quot;)<br>        return .failure(error)<br>    }<br>}</pre><ol><li>The POST and PUT functions both take in the same two inputs, the value you wish to write and the name of the collection you write to. You’ll notice we now require our Generic object to conform to FirebaseIdentifiable. However, it is worth noting that this protocol conforms to Codable which conforms to Decodable so it the same.</li><li>We set up a reference to a new document the collection of our database. We also assign the ID of our value to this document’s ID, and return this value back to the call’s originator to track and handle however you wish.</li><li>We finally set the data of the reference and our value is written! We then return our value in our Result since it’s most up-to-date.</li><li>For our PUT call, since we are trying to access an already existing document, we establish our reference using the value’s ID, which when originally written in Step 2, is also the document’s ID.</li></ol><h4>DELETE Functions</h4><p>Firebase giveth, Firebase take away. Here’s how our deletion code looks to throw into the extension as well (hint: it’s quite similar to POST and PUT).</p><pre>func delete&lt;T: FirebaseIdentifiable&gt;(_ value: T, in collection: String) async -&gt; Result&lt;Void, Error&gt; {<br>    let ref = database.collection(collection).document(value.id)<br>    do {<br>        // 1.<br>        try await ref.delete()<br>        return .success(())<br>    } catch let error {<br>        print(&quot;Error: \(#function) in \(collection) for id: \(value.id), \(error)&quot;)<br>        return .failure(error)<br>    }<br>}</pre><ol><li>Instead of setting data, the Firestore SDK already has it covered with their delete() function. However, if you were to write a nil object using PUT you’d also achieve the same result!</li></ol><h3>3. Polish the API</h3><p>Now that our Generic functions are setup, we can start making some calls specifically for our example data! In this section, you’ll see how we can call each of our Generic functions, as well as some examples or use cases to help you visualize better.</p><h4>Fetching some books</h4><p>Due to the nature of the requests and how the Firestore SDK is structured, I implemented aBookService that mocks out how one would potentially setup the GET requests for single or batched requests:</p><pre>struct BookService {<br>    static func get(by id: String) async -&gt; Result&lt;Book, Error&gt; {<br>        do {<br>            // 1.<br>            let query = FirebaseService.shared.database<br>                .collection(Collections.books.rawValue)<br>                .whereField(&quot;id&quot;, isEqualTo: id)<br>                // Note: You can add more compounding queries here.<br>            <br>            // 2.<br>            let data = try await FirebaseService.shared.getOne(of: Book(), with: query).get()<br>            <br>            return .success(data)<br>        } catch let error {<br>            return .failure(error)<br>        }<br>    }<br>    <br>    static func get(for libraryID: String) async -&gt; Result&lt;[Book], Error&gt; {<br>        do {<br>            // 3.<br>            let query = FirebaseService.shared.database<br>                  .collection(Collections.books.rawValue)<br>                  .whereField(&quot;library_id&quot;, isEqualTo: libraryID)<br><br>            let data = try await FirebaseService.shared.getMany(of: Book(), with: query).get()<br>            return .success(data)<br>        } catch let error {<br>            return .failure(error)<br>        }<br>    }<br>}</pre><ol><li>We structure our query based upon the id we seek to fetch. Notice we can also compound more queries here — learn more by researching the Firebase docs.</li><li>We pass our query into the FirebaseService to retrieve our single piece of data. Easy peasy.</li><li>Similar to step 1 above, we can perform a similar query above, but this time use a different parameter to filter against. From here, we can call FirebaseService to retrieve our batched data.</li></ol><h4>Writing some books</h4><p>Unlike reading from the Firestore, writing is much easier due mostly to not needing queries. You could setup functions within your API layer that call the FirebaseService, but if you wanted to cut straight to the chase, you could call your writes directly from the object itself (!!) thanks to FirebaseIdentifiable.</p><p>This has the opportunity to streamline your code, and make it much more readable. All you’d need to do is direct the object to the right collection:</p><pre>extension FirebaseIdentifiable {<br>    /// POST to Firebase<br>    func post(to collection: String) async -&gt; Result&lt;Self, Error&gt; {<br>        return await FirebaseService.shared.post(self, to: collection)<br>    }<br><br>    /// PUT to Firebase<br>    func put(to collection: String) async -&gt; Result&lt;Self, Error&gt; {<br>        return await FirebaseService.shared.put(self, to: collection)<br>    }<br><br>    /// DELETE from Firebase<br>    func delete(from collection: String) async -&gt; Result&lt;Void, Error&gt; {<br>        return await FirebaseService.shared.delete(self, in: collection)<br>    }<br>}</pre><p>Here you can see they’re extremely similar to one another and just pass through the same Result you’d expect from the FirebaseService itself.</p><h3>Wrap Up</h3><p>Woo! We did it! Or maybe we didn’t and you scrolled to this point in the article. Regardless, to tie a bow on this tutorial, here are some scenario examples to truly demonstrate how easy it is to call the API using this approach. It’s robust yet lightweight — allowing your code to be sustainable as you grow and scale.</p><pre>// ============================================<br>// EXAMPLE STRUCTS... in your models<br>// ============================================<br><br>struct Library: FirebaseIdentifiable {<br>    var id: String<br>    var name: String<br>    var address: String<br>    var books: [String]<br>    var cards: [String]<br><br>    init(<br>        id: String = UUID().uuidString,<br>        name: String = “”,<br>        address: String = “”,<br>        books: [String] = [],<br>        cards: [String] = []<br>    ) {<br>        self.id = id<br>        self.name = name<br>        self.address = address<br>        self.books = books<br>        self.cards = cards<br>    }<br>}<br><br>struct Book: FirebaseIdentifiable {<br>    var id: String<br>    var libraryID: String<br>    var name: String<br>    var author: String<br>    var pages: Int<br>    var isCheckedOut: Bool<br><br>    init(<br>        id: String = UUID().uuidString,<br>        libraryID: String = “”,<br>        name: String = “”,<br>        author: String = “”,<br>        pages: Int = 0,<br>        isCheckedOut: Bool = false<br>    ) {<br>        self.id = id<br>        self.libraryID = libraryID<br>        self.name = name<br>        self.author = author<br>        self.pages = pages<br>        self.isCheckedOut = isCheckedOut<br>    }<br>}<br><br>struct Card: FirebaseIdentifiable {<br>    var id: String<br>    var libraryID: String<br>    var name: String<br>    var expired: Bool<br><br>    init(<br>        id: String = UUID().uuidString,<br>        libraryID: String = “”,<br>        name: String = “”,<br>        expired: Bool = false<br>    ) {<br>        self.id = id<br>        self.libraryID = libraryID<br>        self.name = name<br>        self.expired = expired<br>    }<br>}<br><br>// ============================================<br>// EXAMPLE FUNCTIONS... in your view models<br>// ============================================<br><br>func loadBooks() async {<br>    do {<br>        let books = try await BookService.get(for: someLibrary.id)<br>        // do something with response<br>    } catch let error {<br>        // handle failure<br>    }<br>}<br><br>func create(card: Card) async {<br>    do {<br>      let x = try await card.post(to: Collections.cards.rawValue).get()<br>        // do something with response<br>    } catch let error {<br>        // handle failure<br>    }<br>}<br><br>func update(book: Book) async {<br>    do {<br>        let x = try await book.put(to: Collections.books.rawValue).get()<br>        // do something with response<br>    } catch let error {<br>        // handle failure<br>    }<br>}<br><br>func delete(book: Book) async {<br>    do {<br>        try await book.delete().get()<br>        // do something once deleted<br>    } catch let error {<br>        // handle failure<br>    }<br>}</pre><p>And that’s it — thanks for reading, this was my first article on Medium! I hope you learned something new and consider this architecture in your next iOS project. All feedback is welcome.</p><p><strong>Want to read Part 2?</strong> Check out <a href="https://kylebeard.medium.com/using-realm-to-cache-with-firebase-617f7488380e">Using Realm to cache with Firebase</a> to continue this learning journey and discover how to implement a caching mechanism to save $$$ on those pesky Firebase rate linits and increase the performance of your app!</p><p>In the meantime, check out my products with <a href="https://tigermindlabs.com/">Tiger Mind Labs</a>, or you can find me on: <a href="https://twitter.com/kylebeard_">Twitter</a>, <a href="https://medium.com/linkedin.com/in/kgbeard">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec7e04123c83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/getting-started-with-firebase-using-generics-ec7e04123c83">Getting Started With Firebase Using Generics in Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>