<?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 İrem Tosun on Medium]]></title>
        <description><![CDATA[Stories by İrem Tosun on Medium]]></description>
        <link>https://medium.com/@iremgrel_38434?source=rss-5ec2ef10956c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RXv1AEA8e9aXgKh2gEppBw.jpeg</url>
            <title>Stories by İrem Tosun on Medium</title>
            <link>https://medium.com/@iremgrel_38434?source=rss-5ec2ef10956c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 06:30:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iremgrel_38434/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[Composable Architecture with SwiftUI]]></title>
            <link>https://medium.com/@iremgrel_38434/composable-architecture-with-swiftui-9a837fc3927d?source=rss-5ec2ef10956c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a837fc3927d</guid>
            <dc:creator><![CDATA[İrem Tosun]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 07:44:45 GMT</pubDate>
            <atom:updated>2026-04-10T14:53:58.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*waOhIBjgSRfL3VPuU27tpg.png" /></figure><p>Modern iOS apps are growing fast in size and complexity. As projects scale, managing state, business logic, and navigation becomes harder. This is where <strong>The Composable Architecture (TCA)</strong> shines. It offers a clear and structured way to build applications using SwiftUI.</p><p>In my experience, this architecture is especially ideal for <strong>large and complex SwiftUI projects</strong>. It strongly supports <strong>SOLID principles</strong> and significantly improves <strong>testability</strong>, which are both critical for long-term maintainability.</p><p>You can find a sample implementation of this architecture in the following repository:</p><p><a href="https://github.com/gureli/TCA-Composable-Architecture">https://github.com/gureli/TCA-Composable-Architecture</a></p><h3>Why TCA?</h3><p>TCA provides a unidirectional data flow and enforces strict boundaries between different parts of your app:</p><ul><li><strong>State</strong> — the source of truth</li><li><strong>Action</strong> — all possible user and system events</li><li><strong>Reducer</strong> — where state changes happen</li><li><strong>Environment (Dependencies)</strong> — external services like API clients</li></ul><p>This separation makes your code easier to understand, debug, and test.</p><h3>How is it Different from MVVM?</h3><p>MVVM is already popular in SwiftUI, but TCA takes things a step further.</p><p>In <strong>MVVM</strong>, the main idea is:</p><ul><li>Separate <strong>View</strong> and <strong>Logic (ViewModel)</strong></li></ul><p>However, MVVM often becomes messy in large projects because:</p><ul><li>Logic can grow too much inside the ViewModel</li><li>State changes are not always strictly controlled</li></ul><p>In <strong>TCA</strong>, the separation is more explicit and structured:</p><ul><li>Logic is not just separated from the view</li><li>It is also divided into:</li><li><strong>State</strong></li><li><strong>Action</strong></li><li><strong>Reducer</strong></li></ul><p>This means:</p><ul><li>Every state change is predictable</li><li>All mutations happen in one place (Reducer)</li><li>The code becomes more <strong>readable and traceable</strong></li></ul><p><em>MVVM separates view and logic, while TCA separates logic itself into smaller, well-defined pieces (state, action, reducer), increasing clarity and control.</em></p><h3>The Importance of WithPerceptionTracking</h3><p>WithPerceptionTracking is a key concept when working with TCA and SwiftUI.</p><p>It ensures that:</p><ul><li>Your views only update when the observed state actually changes</li><li>Performance remains efficient</li><li>Unnecessary re-renders are avoided</li></ul><p>Why is this important?</p><p>In large applications:</p><ul><li>State changes frequently</li><li>Without proper tracking, SwiftUI may re-render too much</li></ul><p>Using WithPerceptionTracking:</p><ul><li>Improves performance</li><li>Makes UI updates more predictable</li><li>Helps you avoid subtle bugs</li></ul><p>In short, it is not just a helper — it plays a critical role in keeping your app efficient and scalable.</p><h3>Routing in TCA</h3><p>Routing in TCA is handled through state-driven navigation.</p><p>Instead of imperatively pushing views, you:</p><ul><li>Represent navigation as part of your <strong>state</strong></li><li>Trigger navigation through <strong>actions</strong></li><li>Let the reducer decide what should happen</li></ul><p>This approach:</p><ul><li>Keeps navigation predictable</li><li>Makes it testable</li><li>Avoids hidden side effects</li></ul><h3>Things to Watch Out For 👀</h3><h3>1. Careful Use of @ViewBuilder</h3><p>@ViewBuilder is powerful, but it can lead to problems if overused:</p><ul><li>Avoid putting too much logic inside views</li><li>Keep views simple and declarative</li><li>Move business logic to reducers</li></ul><p>If misused:</p><ul><li>Readability decreases</li><li>Debugging becomes harder</li></ul><h3>2. Keep Reducers Small</h3><p>Reducers can grow quickly in large apps. To avoid this:</p><ul><li>Split features into smaller reducers</li><li>Use composition effectively</li></ul><h3>3. Avoid State Duplication</h3><p>State should have a <strong>single source of truth</strong>:</p><ul><li>Do not duplicate the same data in multiple places</li><li>Keep state minimal and derived when possible</li></ul><h3>4. Think in Data Flow</h3><p>TCA requires a mindset shift:</p><ul><li>Everything flows in one direction</li><li>Actions → Reducer → State → View</li></ul><p>Once you adopt this thinking, the architecture feels much more natural.</p><h3>5. Testing is a First-Class Citizen</h3><p>One of the biggest advantages of TCA:</p><ul><li>Reducers are easy to test</li><li>You can simulate actions and verify state changes</li></ul><p>Make sure to take advantage of this.</p><h3>Conclusion</h3><p>The Composable Architecture is a powerful tool for building scalable SwiftUI applications. It introduces discipline into how state and logic are handled, which becomes essential as projects grow.</p><p>To summarize:</p><ul><li>It is <strong>highly suitable for large and complex SwiftUI projects</strong></li><li>It strongly supports <strong>SOLID principles</strong></li><li>It greatly improves <strong>testability</strong></li><li>It provides a clearer structure than MVVM by splitting logic into smaller parts</li></ul><p>Like any architecture, it has a learning curve. But once understood, it brings clarity, consistency, and confidence to your development process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a837fc3927d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Applying the Chain of Responsibility Pattern in SwiftUI]]></title>
            <link>https://medium.com/@iremgrel_38434/understanding-and-applying-the-chain-of-responsibility-pattern-in-swiftui-d3afd53982de?source=rss-5ec2ef10956c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3afd53982de</guid>
            <dc:creator><![CDATA[İrem Tosun]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 16:39:07 GMT</pubDate>
            <atom:updated>2025-07-23T17:12:57.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCzJnJ90Ktw7O63Shh_QSQ.jpeg" /></figure><p>In this article, I’ll walk you through the <strong>Chain of Responsibility</strong> design pattern — starting with a quick overview of what it is, followed by how I implemented it in a personal SwiftUI project. I’ll then highlight the benefits of using this pattern, share some important aspects, and finally close with a brief note on potential improvements and use cases through brainstorming.</p><h3>🔗 What is the Chain of Responsibility Pattern?</h3><p>The <strong>Chain of Responsibility (CoR)</strong> is a behavioral design pattern that allows an object to pass a request along a chain of handlers until one of them handles it. While the name might sound a bit long and intimidating, its core idea is simple and powerful: it promotes cleaner, more modular, and maintainable code by <strong>decoupling sender and receiver</strong>.</p><h3>What is Decoupling?</h3><p>If you’re unfamiliar with the term “decoupling,” let me explain it with a real-life example. Imagine you’re in an office, and instead of going directly to the manager every time you have a request, you put your request in a tray. Then someone from the team (who’s responsible for that type of request) checks the tray, handles it if they can, or passes it along to the next person.</p><p><strong><em>The person making the request</em></strong><em> (you) is the </em><strong><em>sender</em></strong><em>.</em></p><p><strong><em>The person handling the request</em></strong><em> (your coworkers or manager) is the </em><strong><em>receiver</em></strong><em>.</em></p><p>Now, if you suddenly get a new manager or the company changes how requests are handled, you don’t need to change how <em>you</em> work. You just keep putting requests in the tray.</p><p>That’s what <strong>“decoupling”</strong> means: the sender doesn’t need to know who the receiver is or how the request is handled. Each side can change independently without breaking the whole system. In code, this helps make things more flexible and easier to maintain — because different parts of your app don’t need to know all the details about each other. They just “pass the message along.”</p><h3>🛠 How I Used It in a SwiftUI Project</h3><p>I applied the Chain of Responsibility pattern in <strong>two distinct scenarios</strong> within a SwiftUI project I developed. You can find project details <a href="https://github.com/irem-tosun/cor">here</a>.</p><h4>1. Login Before Adding to Cart</h4><p>The first use case was when a user attempted to add an item to the cart <strong>without being logged in</strong>. In this scenario, the flow first checks the login state. If the user isn’t logged in, they are redirected to the login screen before continuing the action.</p><p>This wasn’t a purely logical flow — it involved UI transitions, so it wasn’t as straightforward as processing simple data. I had to create some custom handling to manage these transitions while still preserving the chain pattern.</p><h4>2. Applying Discount Coupons to Cart Items</h4><p>The second scenario involved applying <strong>discount coupons</strong> to items already in the cart. Here, I used the pattern to apply a sequence of rules or filters in a modular way. This was a simpler use case and illustrated how cleanly CoR can work for pure logic flows.</p><p>In both cases, using the Chain of Responsibility pattern proved to be the <strong>right choice</strong>. It provided a flexible structure and helped reduce code complexity by keeping each responsibility isolated and testable.</p><h3>✅ Benefits and Considerations</h3><p><strong>Advantages:</strong></p><ul><li><strong>Modularity</strong>: Each handler does one job and can be reused or replaced easily.</li><li><strong>Scalability</strong>: Adding or removing steps in the chain doesn’t affect the rest of the system much.</li><li><strong>Clean code</strong>: Helps avoid deeply nested if-else statements.</li></ul><p><strong>What to Watch Out For:</strong></p><ol><li><strong>Correct Order of Handlers</strong><br> The sequence in which you chain handlers matters. In the login-before-add-to-cart example, the LoginHandler had to come <strong>before</strong> the AddToCartHandler. Each handler checks if it should act; if not, it passes the request along.</li><li><strong>Rebuilding the Chain</strong><br> You might need to <strong>reconstruct the chain</strong> dynamically, especially when dealing with screens and navigation in SwiftUI. Flexibility here is key.</li><li><strong>Termination of the Chain</strong><br> Always ensure the <strong>last handler in the chain has no </strong><strong>next handler</strong> to avoid infinite loops. Your chain must have a clear end.</li></ol><h3>🧠 Final Thoughts &amp; Brainstorming</h3><p>The Chain of Responsibility pattern is a great tool when used in the right place. In UI-based applications like SwiftUI, it can be adapted not only for backend logic but also for <strong>flow control</strong> and <strong>user interaction handling</strong>.</p><p>To wrap up, always remember:</p><ul><li>Use the pattern <strong>only when it makes sense for your problem</strong>.</li><li>Think about future extension — how easily can a new rule or handler be added?</li><li>Watch out for side effects when dealing with UI transitions inside the chain.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3afd53982de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Techniques for Web Debugging: Test doubles]]></title>
            <link>https://medium.com/@iremgrel_38434/essential-techniques-for-web-debugging-test-doubles-bdf70ce1cdbf?source=rss-5ec2ef10956c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdf70ce1cdbf</guid>
            <dc:creator><![CDATA[İrem Tosun]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 13:34:28 GMT</pubDate>
            <atom:updated>2024-12-04T13:34:28.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*F8xtFoTblFlTxZK3NMYSbA.jpeg" /></figure><p>Testing is crucial while developing a software. As mobile developers, we need to debug and test our features in order to make sure our app is prepared for different situations. Testing can sometimes be tricky, especially if you are debugging web related stuff. That is where test doubles come into the picture. Let’s dive deep into it!</p><h3>Dummy</h3><blockquote>A dummy is an object that is passed around but never actually used. It is typically used to fill parameter lists or satisfy protocol requirements.</blockquote><p><strong>Example:</strong></p><p>In a method that requires a non-null variable but doesn’t actually interact with it, you might use a dummy.</p><pre>protocol Product {<br>    <br>}<br>protocol PurchaseService {<br>    func buyProduct(_ product: Product)<br>}<br><br>struct DummyProduct: Product {<br>    let id: Int = 0<br>    let name: String = &quot;&quot;<br>    let price: Double = 0<br>    let description: String = &quot;&quot;<br>}<br><br>// Let&#39;s say you have a mock service that is implemented<br>class MockPurchaseService: PurchaseService {<br>    func buyProduct(_ product: Product) {<br>        <br>    }<br>}</pre><pre>  let purchaseService = MockPurchaseService()<br>    let product = DummyProduct()<br>    purchaseService.buyProduct(product)</pre><p>And this is how we make use of dummy test double. Obviously, the goal is just to be able to confirm PurchaseService protocol.</p><h3>Stub</h3><blockquote>Suppose you’re developing a software application that relies on a database connection, but the database system isn’t ready yet. Then you can create a mock HttpClient that simulates the behaviour of the database connection. Don’t let the keyword “<em>Mock</em>” confuse you here, the technique I am talking about is <strong><em>Stub</em></strong>.</blockquote><p>I would like to demonstrate to you how to simulate your HttpClient without actually performing any database operations. This mock HttpClient will return us dummy data, some predefined responses to mimic the expected behaviour of the real database connection.</p><p>While doing this I am going to prefer injecting with Environment in SwiftUI. We definitely require a <strong><em>protocol</em></strong> in each of the methods.</p><pre><br>import Observation<br><br>protocol CharacterService {<br>    var figureList: [Figure] { get }<br>    func fetchAll(page: Int) async throws<br>}<br><br>@Observable final class MockCharacterService: CharacterService {<br>    var figureList: [Figure] = []<br><br>    func fetchAll(page: Int) async throws {<br>        let figures: [Figure] = try await withCheckedThrowingContinuation { continuation in<br>            Task {<br>                let figures: [Figure] = MockDataProvider.loadList(resourceName: &quot;characters&quot;)<br>                continuation.resume(returning: figures)<br>            }<br>        }<br>        figureList = figures<br>    }<br>}</pre><p>MockCharacterService is a mock service designed to provide fake data for testing purposes. Instead of generating random or dynamic data, I use a <strong>Stub</strong> technique, which relies on stable, predefined data. In this case, the data is sourced from a static JSON file included in the main or test bundle. This ensures consistency and repeatability in tests, as the input data remains unchanged across test runs, making it easier to verify expected outcomes and debug issues.</p><pre>struct MockDataProvider {<br>    static func load&lt;T: Decodable&gt;(resourceName: String) -&gt; T {<br>        guard let path = Bundle.main.path(forResource: resourceName, ofType: &quot;json&quot;) else {<br>            fatalError(&quot;Resource \(resourceName) does not exist&quot;)<br>        }<br>        let data = try! Data(contentsOf: URL(filePath: path))<br>        return try! JSONDecoder().decode(T.self, from: data)<br>    }<br>}</pre><pre>extension EnvironmentValues {<br>    var listService: CharacterService {<br>        get { self[CharacterServiceStateKey.self] }<br>        set { self[CharacterServiceStateKey.self] = newValue }<br>    }<br>}<br><br>private struct CharacterServiceStateKey: EnvironmentKey {<br>    static var defaultValue: CharacterService = CharacterServiceImpl()<br>}</pre><p>Then inject the protocol into your view. Using SwiftUI’s environment for dependency injection is flexible and intuitive. It lets you easily switch between mock services for testing and real services for production. This approach simplifies testing and keeps your code clean and decoupled.</p><pre>struct CharacterDetailView: View {<br>    @Environment(\.sizeCategory) var sizeCategory<br>    @State private var viewModel: CharacterDetailViewModel<br>    @Environment(\.detailService) private var characterService: CharacterDetailService</pre><pre>#Preview {<br>    CharacterDetailView(id: &quot;3&quot;)<br>        .environment(\.detailService, MockCharacterDetailService())<br>}</pre><h3>Why Use a Stub?</h3><ul><li><strong>Predictability</strong>: The data is static and controlled, avoiding the unpredictability of randomly generated inputs.</li><li><strong>Repeatability</strong>: Tests using the same stubbed data will always yield the same results, making test outcomes reliable.</li><li><strong>Ease of Debugging</strong>: Since the data doesn’t change, any test failures can be traced back to the implementation rather than the data source.</li><li><strong>Consistency Across Environments</strong>: Whether running tests locally or in a CI pipeline, the same stubbed JSON file ensures uniform results.</li></ul><h3>Fake</h3><blockquote>Assume a software program connects with a third-party payment gateway to perform purchases. Rather than using the real payment gateway during testing, which may generate real charges or require a consistent internet connection, a fake payment gateway can be used. The fake payment gateway aligns with the behavior of the real one, allowing the application to be tested without committing actual expenses or relying on third-party services.</blockquote><p>You can use the same injection techniques as dependency injection or using environment when using Fakes. However, you are not supposed to store static json data in your app for fakes. Please keep in mind that Fakes and Stubs are not the same thing.</p><p><strong>Difference between Fake and Stub:</strong></p><p>While stubs provide hardcoded and static responses, fakes are more complex and may contain some degree of actual business logic.</p><p>While stubs are very simple and they have no real logic, fakes are more complex and may contain simplified logic to mimic real behavior.</p><p>While stubs are hardcoded ans static reponses, fakes are more realistic as they can perform operations that a real object would do, such as storing data in memory instead of a database.</p><p><strong>Result:</strong></p><p>Fakes mimic the behavior of real components but in a simplified manner.</p><h3>Spy</h3><blockquote>A <strong>spy</strong> is a test double used to verify that specific methods or properties were accessed or modified during the execution of a test.</blockquote><p>Unlike a mock, which simulates behavior and verifies interactions upfront, a spy passively observes and records interactions during a test, allowing you to verify these interactions afterward. Spies are particularly useful when you want to:</p><ul><li>Confirm that a method or callback was invoked under certain conditions.</li><li>Ensure that a dependency received specific parameters when called.</li><li>Track property changes or updates in a class or object.</li><li>Validate user interactions, such as tapping on a UI component, triggering a function, or modifying state.</li></ul><p>The component itself can act as a “spy” if its behavior is designed in a way that allows you to observe interactions or state changes directly without creating a separate test double. This approach works when the component provides enough access to its internal state or uses a callback mechanism that can be inspected during tests.</p><p>Below is an example of a unit test where the CustomHeaderView component acts as a spy to verify its own behavior.</p><pre>func testTapGestureUpdatesSelectedItem() {<br>    // Given<br>    enum MockItem: HeaderProtocol {<br>        case item1, item2, item3<br><br>        var description: String {<br>            switch self {<br>            case .item1: return &quot;Item 1&quot;<br>            case .item2: return &quot;Item 2&quot;<br>            case .item3: return &quot;Item 3&quot;<br>            }<br>        }<br>    }<br><br>    let items: [MockItem] = [.item1, .item2, .item3]<br>    let headerView = CustomHeaderView(items: items)<br>    let initialSelection = headerView.getSelectedItem()<br><br>    // When: Simulate a tap on the second item<br>    let selectedItem = .item2<br>    let tapGestureWithItem = TapGestureRecognizer&lt;PeriodType&gt;(target: headerView, action: #selector(headerView.didTapSection(_:)))<br>    tapGestureWithItem.item = selectedItem<br><br>    headerView.didTapSection(tapGestureWithItem)<br>    let selectionAfterGesture = headerView.getSelectedItem()<br><br>    // Then<br>    XCTAssertNil(initialSelection, &quot;The initial selection should be nil&quot;)<br>    XCTAssertEqual(selectionAfterGesture, .item2, &quot;The callback should receive the second item&quot;)<br>}</pre><h3>Mocks</h3><blockquote>Mocks are particularly useful in unit testing when you need to verify that the interactions between your system under test (SUT) and its dependencies occur as expected.</blockquote><p>Mocks actually act like fakes and stubs in the way they need to make the SUT believe it’s talking with its real collaborators — but mocks differ in the setup and the verification phases.</p><p>Using a <strong>mock server</strong> offers:</p><ol><li><strong>Dynamic flexibility</strong>: Easier to simulate a wide range of scenarios without hardcoding every response.</li><li><strong>Realism</strong>: Simulates real-world conditions like delays, errors, or invalid data.</li><li><strong>Request validation</strong>: Tracks and validates outgoing API calls.</li><li><strong>Error handling</strong>: Easily tests edge cases and unexpected scenarios.</li><li><strong>Team collaboration</strong>: Centralized and reusable.</li></ol><p>You can setup mock server for your MockServer needs. Please have a look at my previous article about <a href="https://medium.com/adessoturkey/debugging-chronicles-postman-for-network-debugging-cc36b9fc9bfd#bd00">setting up Mock Servers in Postman.</a></p><pre>class MockServer {<br>    private var routes: [String: (URLRequest) -&gt; (statusCode: Int, data: Data?)] = [:]</pre><pre>    func addRoute(path: String, response: @escaping (URLRequest) -&gt; </pre><p>Mocks offer more flexibility and powerful features for testing, but if you only need simple behavior for your tests, a stub can be a more lightweight option.</p><p>Mock server can simulate a variety of error scenarios (e.g., unauthorized access, server overload) on the fly.</p><p>Mock service acts as a centralized source of mock data, which can be shared across developers, testers, and CI pipelines. This approach allows for dynamic responses, error simulation, and better test coverage compared to a stub.</p><h3>Summary</h3><p>In this article, we explored the concept of test doubles and their critical role in unit testing. We covered the different types of test doubles, including stubs, mocks, spies, and fakes, each with its own specific use case and level of complexity. I also highlighted some of the advantages of using mocks over stubs. However, it’s important to recognize that the choice between mocks and stubs depends on the specific requirements of your tests. At some point the complexity of your testing requirements and the things you want to verify in your code will affect which tool is best for the job.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdf70ce1cdbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memento Design Pattern: Is It the Right Choice for Your State Management Needs?]]></title>
            <link>https://medium.com/@iremgrel_38434/memento-design-pattern-is-it-the-right-choice-for-your-state-management-needs-4a6f5622297a?source=rss-5ec2ef10956c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a6f5622297a</guid>
            <dc:creator><![CDATA[İrem Tosun]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 06:11:19 GMT</pubDate>
            <atom:updated>2024-11-14T07:56:25.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDgNhN4WG6m4hv8Jv_f49Q.png" /></figure><p>Memento design pattern is a powerful tool for state preservation. It is a behavioral design pattern that allows an object to save and restore its previous state without exposing its internal details. It is commonly used for implementing undo/redo functionality or for preserving history within an application.</p><h3>How It Works:</h3><ul><li>The <strong>Originator</strong> creates a <strong>Memento</strong> object that stores its current state.</li><li>The <strong>Caretaker</strong> holds onto the memento, potentially saving a series of mementos to allow rolling back to previous states.</li><li>When necessary, the <strong>Originator</strong> can restore its state from a previously stored memento.</li></ul><h3>Is It the Right Choice?</h3><p>Determining the right design pattern is crucial for building efficient and maintainable software. The <strong>Memento pattern</strong> can be highly effective when used in the right context but can introduce unnecessary complexity when misapplied. For instance, in a <strong>drawing app</strong>, the Memento pattern is perfect for implementing undo/redo functionality. Each time a user makes a brush stroke or change to the canvas, a snapshot of the drawing’s state can be saved without exposing the app’s internal structure. This allows users to easily revert to previous versions of their artwork by restoring those saved states, making the pattern a natural fit for this scenario.</p><p>You can take a look at my <a href="https://github.com/iremgureltosun/mementoCase">sample project</a> where I have provided a generic structure for Caretaker and Memento, serving for 2 different cases. My view models served as originators.</p><p>Drawing view presents the efficient use of memento pattern. Each memento is captured as user makes a new drawing to the panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*MxrXLUS05fSsE_LfNOrzIw.jpeg" /></figure><p>In article generator, I saved file names instead of entire data for memory efficiency. We are able to view different versions of a file with this example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*hNvHvlXiwrLlJYrNr4-V9A.png" /></figure><h3>Some Challenges and Criticism</h3><h4>Memory Overhead</h4><p>Storing multiple snapshots of an object’s state can significantly increase memory usage, especially when objects have large or complex states. If an application needs frequent state captures, such as for undo/redo functionality, the number of mementos can grow quickly, leading to memory constraints. To mitigate this, developers often need to implement strategies like limiting the number of stored mementos or compressing state information​</p><h4>Inconsistent State</h4><p>Without careful management, restoring an earlier state using a memento can sometimes result in inconsistencies. For example, if external resources or references change while a state is saved, restoring the memento may bring back an invalid or broken state. Proper management of dependencies and object lifecycle is required to avoid such pitfalls​.</p><h4>Lack of Scalability</h4><p>The Memento pattern may not scale well in situations where the internal state of the object is large or the number of objects needing state saving grows significantly. The more states or objects that require state preservation, the more resource-intensive the system becomes, complicating implementation and potentially limiting scalability</p><h3>Similar Pattern that Interacts with State</h3><p>There are two other patterns similar to the Memento pattern. I am not using the word ‘alternative’ here because they don’t serve exactly the same function.</p><h4><strong>Command Pattern</strong></h4><p><strong>Well-suited scenario:</strong> A great example would be a <strong>shopping cart</strong>, particularly when you want undo/redo functionality for actions like adding, removing, or updating items. By encapsulating each action as a command, it allows the system to track a sequence of discrete actions, making it simple to reverse or reapply each step.</p><p>This approach is more efficient for a shopping cart than the Memento pattern, which is designed to save the entire state of an object. Using Memento would mean capturing the full cart state each time a change is made, which could be inefficient and memory-intensive as the cart grows or changes frequently. In contrast, the Command pattern only records individual actions, providing a lightweight, targeted solution for managing user interactions in the cart without needing to track every version of its entire state.</p><p><strong>Benefits:</strong></p><ul><li><strong>Less Memory Overhead</strong>: Instead of saving entire states, you store only the operations.</li><li><strong>Simplicity</strong>: The pattern allows simpler management of undo/redo operations through reversible commands.</li></ul><h3>Similar Pattern that Manages State</h3><h3><strong>State Pattern</strong></h3><p><strong>State pattern</strong> is when an object’s behavior depends on its internal state, and it must change behavior at runtime based on that state.</p><p><strong>Well-suited scenario:</strong> A betting ticket can have different states — <em>Preparing</em>, <em>Pending</em>, <em>Confirmed</em>, or <em>Cancelled</em>. Based on these states, the options presented to the user and the behavior in the interface change accordingly.</p><ul><li>For example:</li><li>In the <em>Preparing</em> state, the user can edit the bet details.</li><li>In the <em>Pending</em> state, the user can cancel the bet but not edit it.</li><li>In the <em>Confirmed</em> state, all changes are locked, and the user may only view the details.</li><li>In the <em>Cancelled</em> state, the bet is no longer accessible for any action, only for viewing.</li></ul><p><strong>Benefits: </strong>In this scenario, the State pattern helps manage the dynamic behavior of the betting app, ensuring that the interface and actions align with the current state of the ticket.</p><h3>Conclusion</h3><p>In this article, I aimed to explain the Memento design pattern and its challenges. While design patterns offer powerful solutions to complex problems, it’s important to remember that selecting the right pattern for your specific needs is just as critical. Applying a pattern simply because it seems ‘cool’ can lead to unnecessary complexity. Always consider the problem at hand and choose the pattern that fits best.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a6f5622297a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging Chronicles: Debugging with Proxy Tools]]></title>
            <link>https://medium.com/adessoturkey/debugging-chronicles-debugging-with-proxy-tools-7c740bd39cf0?source=rss-5ec2ef10956c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c740bd39cf0</guid>
            <dc:creator><![CDATA[İrem Tosun]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 11:21:38 GMT</pubDate>
            <atom:updated>2024-07-16T06:36:43.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4bdp-uvt-KENepYkkNdNw.jpeg" /></figure><p>Debugging is a vital skill for any developer navigating the ever-evolving landscape of software development. In this article, I will demonstrate how to debug network requests and responses while developing mobile applications. Using Proxyman as our primary tool, I’ll provide examples across various scenarios to illustrate its capabilities. By the end, you’ll gain a comprehensive understanding of when and why proxy tools like Proxyman are indispensable.</p><h3>What are Proxy Servers?</h3><p>Proxy server operates as a “man-in-the-middle”. This means that it intercepts communication between a client (such as a mobile device or computer) and a server. By sitting between the client and the server, it can capture and analyze the traffic passing through it, allowing developers to inspect, modify, and simulate network requests and responses. This capability is particularly useful for debugging and testing purposes in mobile and web development, as it provides visibility into the data being exchanged and enables developers to identify and address issues more effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*fEkZNOFh2oT86ALa6IatAA.png" /><figcaption>Recommended proxy tools that are paid.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*SmQWG4hINWE2s5z6LAqM0A.png" /><figcaption>Recommended proxy tools that are free.</figcaption></figure><h3>Debugging Network Responses with Proxyman</h3><p>With the power to monitor, analyze, and manipulate HTTP/HTTPS requests, Proxyman is a robust and easy-to-use proxy tool that can greatly improve your debugging skills.</p><h4>Scenario 1: Debug How to Handle an Irreproducible Case</h4><blockquote>The backend changed the implementation and decided not to send episodes anymore. We do not have such a record in the real environment and are unable to debug it with any of the records. This is when Proxyman’s Map Local tool comes into play.</blockquote><p>In order to start mocking with Proxyman, you first need to install Proxyman’s certificate onto the device you are going to use for debugging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*kZvEHkyMDQupbgW4jv20rQ.png" /><figcaption>First step is to make sure proxyman certificate is installed on device/simulator.</figcaption></figure><p>Check if it’s working as expected: I can inspect the web responses like that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aomoe3M3Z014Z98wvE37mg.png" /><figcaption>I am able to inspect the responses after running the app in debug mode.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*O_rXcC32gg3x4ic-b_0eGA.png" /><figcaption>Original display of the record that I am going to mock.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wp1JjjWMoKdkSL3ZArievQ.png" /><figcaption>Original display of the corresponding record before mocking.</figcaption></figure><p>Now let’s modify the response of the record with id 20.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkDMsVUYBDHyF3XadsJTnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9wfQjbPgkMQLcBOIdfRvA.png" /><figcaption>Configuring the endpoint that I want to mock.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgX9vDBxiwPaeNUqm07vnA.png" /><figcaption>I removed the episodes information completely.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjh9mIOCn5CTLUn7-Vlo8Q.png" /><figcaption>Make sure you select enable Map Local Tool and the configuration you want to activate below.</figcaption></figure><p>Let’s re-run and see how it responds. I am expecting to encounter a bug since I haven’t taken any actions for that case before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RirYEgYmhAKKCBj4wIPWNA.png" /><figcaption>I see the expected error when I try to open the related record now.</figcaption></figure><h4>Time to Fix:</h4><p>Now let’s figure out how to fix the bug for this case. In my current implementation, I never expect episode field to be absent, so my decoder expects to decode each coding key. Now that the episodes has become optional, it is time to make it optional.</p><pre>import Network<br><br>struct Figure: HTTPResponseProtocol {<br>    typealias HTTPEntityType = Figure.Type<br><br>    let id: Int<br>    var name: String<br>    let status: CharacterStatus<br>    let species, type: String<br>    let gender: CharacterGender<br>    let origin, location: Location<br>    let image: String<br>    let episode: [String]?<br>    let url: String<br>    let created: String<br><br>    enum CodingKeys: String, CodingKey {<br>        case id<br>        case name <br>        case status<br>        case species<br>        case type<br>        case gender<br>        case origin<br>        case location<br>        case image<br>        case episode<br>        case url<br>        case created<br>    }<br>}</pre><pre>let episode: [String]</pre><p>By making this variable optional, the app will be able to handle this edge case without any crashes or unexpected behavior.</p><pre>let episode: [String]?</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*fu-CGZzfPIDFBrzYTn1uNg.png" /><figcaption>Fixed the bug when episodes list is not received at all from the web api.</figcaption></figure><h4><strong>Scenario 2: When a New Feature Added</strong></h4><blockquote>Suppose the product owner has added a new feature. All of its details have been determined; however, the backend has not published the change yet. You can save time by using Map Local to debug the new feature.</blockquote><p>In my example, I am going to add a new variable to Figure called hobbylist.</p><pre>enum Hobby: String, Codable, CaseIterable {<br>    case sports<br>    case music<br>    case dance<br>    case baseball<br>    case picnic<br>    case movies<br>    case art<br>    case travelling<br>    case gardening<br>}</pre><pre>import Network<br><br>struct Figure: HTTPResponseProtocol {<br>    typealias HTTPEntityType = Figure.Type<br><br>    let id: Int<br>    var name: String<br>    let status: CharacterStatus<br>    let species, type: String<br>    let gender: CharacterGender<br>    let origin, location: Location<br>    let image: String<br>    let episode: [String]<br>    let url: String<br>    let created: String<br>    let hobbyList: [Hobby]?<br>}</pre><p>I need to make this field optional, since it won’t be implemented for real in my example.</p><pre>let hobbyList: [Hobby]?</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*JFOYlr2DdAJ0NvKPZneolg.png" /><figcaption>Added the new feature hobbyList to mock response.</figcaption></figure><p>Then, when I run the project and set a breakpoint inside my getCharacter function, I can see the hobbyList as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*deP0b27If8zw2n4dEan9oA.png" /><figcaption>HobbyList is decoded successfully with the mock response.</figcaption></figure><h3>Time to Use HttpClients</h3><p>In scenarios where you don’t have a server to intercept, you can indeed use HTTP clients to simulate server responses. By using HTTP clients, you can create mock responses and simulate various server behaviors without needing an actual backend server. This approach is particularly useful during early stages of development or when backend services are unavailable.</p><h4>Debug When Production API is not ready</h4><p>Mock servers are essential for ensuring seamless development, testing, and prototyping processes when the backend is not yet ready or available. Tools like Postman Mock Server, JSON Server, Mockoon, WireMock, and Mountebank provide various options to create and manage mock APIs efficiently. By using these HttpClient tools, you can work independently of backend constraints, leading to faster and more reliable project delivery.</p><p>If you are interested in using <strong>Postman Mock Server</strong>, you can take a look at <a href="https://medium.com/@iremgrel_38434/debugging-chronicles-postman-for-network-debugging-cc36b9fc9bfd#3ce6">this article</a> where I provide detailed instructions on how to configure a mock server in Postman.</p><h3>Summary</h3><p>If you are interested in debugging in terms of all aspects, please take a look at my previous articles as well.</p><p><a href="https://medium.com/@iremgrel_38434/debugging-chronicles-postman-for-network-debugging-cc36b9fc9bfd">Postman for Network Debugging</a></p><p><a href="https://medium.com/@iremgrel_38434/debugging-chronicles-a-journey-into-view-layer-debugging-mastery-c642d299c5f2">A Journey into View Layer Debugging Mastery</a></p><p><a href="https://medium.com/@iremgrel_38434/debugging-chronicles-exploring-breakpoints-conditions-lldp-commands-and-watchpoints-50987096dc3d">Exploring Breakpoints, Conditions, LLDP Commands, and Watchpoints</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c740bd39cf0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/debugging-chronicles-debugging-with-proxy-tools-7c740bd39cf0">Debugging Chronicles: Debugging with Proxy Tools</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging Chronicles: Postman for Network Debugging]]></title>
            <link>https://medium.com/adessoturkey/debugging-chronicles-postman-for-network-debugging-cc36b9fc9bfd?source=rss-5ec2ef10956c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc36b9fc9bfd</guid>
            <dc:creator><![CDATA[İrem Tosun]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 08:32:43 GMT</pubDate>
            <atom:updated>2024-07-16T06:36:58.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2n_YEOoArU9TCcDL5N6XMA.png" /></figure><p>Postman is an HTTPClient that we might use for a variety of reasons. As a mobile developer, I use Postman when there is a lack of documentation, a network-related fault that needs to be reported to a colleague, or to save time when converting a json structure into request/response bodies. For these reasons, I want to share some awesome Postman tips with you today. Below is our roadmap highlighting the topics we’ll cover. Now let’s get started! 🚀</p><p>− <a href="#e35e">Postman: Unleashing the Power of Debugging Network Operations</a><br>− <a href="#6dca">Data Driven Testing with Postman</a><br>− <a href="#84d8">Adding Test Scripts</a><br>− <a href="#774c">Authorization</a><br>− <a href="#8c59">Essential Security Tip for Authorization</a><br>− <a href="#e49f">Convert JSON to Swift Models</a><br>− <a href="#3ce6">Creating a Mock Server</a><br>−− <a href="#b83d">Step 1: Create a New Collection</a><br>−− <a href="#fcf0">Step 2: Add Example</a><br>−− <a href="#bd00">Step 3: Add Mock Server</a><br>−− <a href="#92ff">Step 4: Configure Your Client</a></p><h3>Postman: Unleashing the Power of Debugging Network Operations</h3><p>Postman can be used for API development, testing, and management, and it is available both as a browser-based tool and as a desktop app. In Postman, Workspaces help you organize your API work and collaborate with others across your organization or around the world.</p><p>The Postman UI consists of four main sections: the Header, Sidebar, Builder, and Status Bar. Within Postman, you can group requests under Collections, which can be downloaded as JSON files, exported, and shared with anyone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F7V-OtOkVGueJUDRRUOqAg.png" /><figcaption>You see the sections of Postman. I am defining a new variable.</figcaption></figure><p>Postman variables are key-value pairs that improve reusability by letting you store and use commonly used or common values. It is efficient to store all common and repeated values in variables since they allow for the advantage of making changes in one place when a variable is being used in different contexts. Variables can be referenced in requests, scripts, collections, and environments. They can be generated at the following scopes: global, collection, environment, data, and local.</p><p>Please remember that it’s not crucial to include variables. To keep things more organized, I’m going to demonstrate this functionality to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UkDTaOt3qvbzLZSQ7fwoVg.png" /><figcaption>I am updating my get request by using a variable.</figcaption></figure><h3><strong>Data Driven Testing with Postman</strong></h3><p>You can insert a csv/json file to execute multiple requests.<br>You need to first run collection in order to start data-driven testing. I will make an effort to provide screenshots for each detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*PmSliu1EWNZ0ObIN8-7dzg.png" /><figcaption>Select run collection from the opened pop-up.</figcaption></figure><p>You are more aware of your needs. In my situation, all I need is a header field for a receive request. I only defined an endpoint, though.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*Hbg0acwgmCKVodwQanW0NA.png" /><figcaption>I prepared a json file for my test.</figcaption></figure><p>This is how I input every endpoint that I wanted to test. I afterwards saved it as a JSON file. If you’d like, you can alternatively create a CSV file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*sVNTtrQ25JxmmnklpmH8Ow.png" /><figcaption>You can either create a csv file if you want to.</figcaption></figure><p>When you view the preview data, everything appears to be clear and in order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*tjSuw2MVjLryiudkMBxkBA.png" /><figcaption>The preview data is like that.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyRDTmPlOZXzr8m-s278yw.png" /><figcaption>I selected the request that I want to run the test.</figcaption></figure><p>Finally, I specify that when using a script like this, I expect to receive a status code of 200. Last but not least, I also define that I expect status code 200 with a script like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*lCNSmkKaUfOf58hy4VSkkA.png" /></figure><p>Now let’s run and see if the requests work as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cW3hCwNFBAPLw74QH3AP-Q.png" /><figcaption>Tests succeeded and gave me the expected status code.</figcaption></figure><h3><strong>Adding Test Scripts</strong></h3><p>Scripts are useful for verifying whether your requests meet your expectations. For instance, I have a similar endpoint that provides me with the characters organized by page number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qmhct5hEo2EhhAPhymWLxQ.png" /></figure><p>I anticipate receiving a 200 status code from this endpoint and a response within a specific time frame. I therefore defined test scripts in the tests section in that manner. You are free to define anything you require.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*rHZEzKPvLQqqHDf7Qit6dA.png" /><figcaption>Scripts ran and gave me the expected results.</figcaption></figure><p>After the definition, I can view the test results in my console after saving and running it.</p><h3>Authorization</h3><p>Authorization in Postman is essential for accessing secured APIs, ensuring that requests have the necessary permissions. Postman supports several types of authorization methods to cater to different security requirements:</p><ol><li><strong>API Key</strong>: A simple and commonly used method where a key is included in the request header or URL to authenticate the client.</li><li><strong>Bearer Token</strong>: This method uses a token, typically a JSON Web Token (JWT), included in the request header to verify the user’s identity and permissions.</li><li><strong>Basic Auth</strong>: A straightforward method where the username and password are encoded in Base64 and sent in the request header.</li><li><strong>Digest Auth</strong>: A more secure alternative to Basic Auth that involves sending a hashed version of the credentials, providing protection against replay attacks.</li><li><strong>OAuth 1.0</strong>: An older protocol used for authorization, involving multiple steps to obtain an access token for authenticating requests.</li><li><strong>OAuth 2.0</strong>: A more modern and widely used protocol that provides various flows (such as Authorization Code, Implicit, Password Credentials, and Client Credentials) to obtain access tokens for secure API access.</li><li><strong>Hawk Authentication</strong>: A method similar to OAuth but simpler, using a cryptographic algorithm to create request signatures.</li></ol><p>I am going to demostrate you how to configure your postman with a Bearer token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZ0Kqw7rAElji10gznquoA.png" /></figure><p>Using the Bearer token definition, I was able to successfully obtain the response. But this isn’t configured in any way. It would be more efficient to use environment variables and store the token securely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*WhjV17jVv5p8y8uluZ5y3Q.png" /><figcaption>Click on edit.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*xDFp0JWHt6B-uoXAzQE7Kw.png" /><figcaption>You can define your token at collection level.</figcaption></figure><h3>Essential Security Tip for Authorization</h3><p>If you want to share your queries with another member of your team, it may be necessary to do so discreetly.<br>You can construct an environment variable for this, and just enter the token into the current value field while entering a definition into the initial value field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUOH3kIyIo-EBw2kkonOvA.png" /><figcaption>Token should be stored in the current value field.</figcaption></figure><p>After defining the secret token value in the environment, you should first select your environment, then enter your variable name in order to use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*wuOZ_aYBBDCYkXPSPgPkrg.png" /><figcaption>Make sure you select the environment on the right hand corner.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*FOtKfLC6PdcKjMrQNlzzLw.png" /><figcaption>Variable name is token in my case.</figcaption></figure><p>Now, token is not exposed and we can use it securely.</p><h3>Convert JSON to Swift Models</h3><p>Postman can convert an API request into a code snippet in a programming language in just a few clicks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qqqJ92PJilP47JXv1csQQ.png" /><figcaption>You can generate requests with Postman.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*SZkE7sRqguFC1q4TV4lTWg.png" /><figcaption>You can edit this code snippet according to your privileges.</figcaption></figure><p>Unfortunately, I could not discover any support for Responses right now, but don’t worry, it is still fairly simple to convert. I use <a href="https://jsonformatter.org/json-to-swift">jsonformatter.org</a></p><p>And it is your privilege to give any name to your models; just make sure to change the references correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOWIs-JL5No5qxpEozmDdQ.png" /></figure><h3>Creating a Mock Server</h3><p>Creating a mock server is essentially in cases when you don’t have any working backend environment or published version of an endpoint that you need. I am going to use postman-echo.com in order to define my requests. postman-echo.com is a service provided by Postman that allows you to test your REST APIs by making various types of requests.</p><h4>Step 1: Create a New Collection</h4><p>Let’s start by creating a new collection for the mock server to-be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RsoB0afEmVflHCxq" /><figcaption>The base endpoint that I prefer is <a href="https://postman-echo.com/">https://postman-echo.com</a></figcaption></figure><p>I don’t have any endpoints right now, since backend is unavailable. So I just go a head and enter <a href="https://postman-exho.com/get">https://postman-echo.com/get</a> and save this request. As you see, it returns me a successful response.</p><h4>Step 2: Add Example</h4><p>Next step is to save the response as example by pushing the button “Save as Example” button, since I want to add different requests and mock responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/0*iDSIA2jKVfiX3Un0" /><figcaption>Select Add example option</figcaption></figure><p><strong>Example Request 1: Get users</strong></p><p>Now I changed the url as<a href="https://postman-exho.com/get"> </a><a href="https://postman-echo.com/getUsers">https://postman-echo.com/getUsers</a> then entering my json response to the bottom field. However this will not work before I enter a mock server for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ok5F7zGxuUQ56v0E" /><figcaption>Configure it like that, it will work after mock server is ready.</figcaption></figure><h4>Step 3: Add Mock Server</h4><p>I simply tap the Mock Servers button on the left hand side. If you cannot see it, you can tap on the last + button to display it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/0*Pf-s_Lie0b0KftRO" /><figcaption>Create your mock server.</figcaption></figure><p>I am selecting my Mock Collection where my mock endpoint is defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/0*42gmpMBurDzTcBF5" /></figure><p>I am filling the required fields and finalizing the creation by pushing the create mock server button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*RvSAFmsK26TJbOGk" /></figure><p>Now you are supposed to see this view where the url of the mock server is mentioned. Copy it for further configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*BX8Zt-pYPxKs5fDp" /></figure><p>Now that you have created your mock server, go back to the collection and replace the <a href="https://postman-exho.com/get">https://postman-echo.com/</a> url with the mock server url that you have recently captured, save and try.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0PgXSmKrTog-7Vsx" /></figure><p>Congratulations! Now we have a functioning mock server. The further step is to use it from client.</p><p><strong>Added more requests: Get appointments of each user</strong></p><p>I have added more requests and mock responses to display appointments of each user and used the same mock server url for each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uSE8nP6GYMq2adYgchERg.png" /></figure><h4>Step 4: Configure Your Client</h4><p>I configured my url requests as follows. You can integrate your own logic depending on your needs. Feel free to download/inspect my <a href="https://github.com/iremgureltosun/Benchtime">reference project</a>.</p><pre>struct UserMockAPI {<br>    enum ApiConfig {<br>        private static let baseURL: String = &quot;https://fdc39d9d-cbf6-4ce2-b0dd-3861a530172a.mock.pstmn.io/&quot;<br><br>        case all<br>        case appointments(userId: String)<br><br>        var url: String {<br>            switch self {<br>            case .all:<br>                return &quot;\(Self.baseURL)getUsers&quot;<br>            case let .appointments(userId):<br>                return &quot;\(Self.baseURL)getAppointments/?userId=\(userId)&quot;<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*BOLpxdjqbUQbNvI5NX4c2w.png" /><figcaption>Displayed users fetched from mock server.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*d27bjcNyw9jU_bUygxUDqw.png" /><figcaption>Displayed appointments of users fetched from mock server.</figcaption></figure><p>Everything works as expected, and I’ve already implemented the feature despite not having a real backend at the moment. Postman’s mock server tool provides us with the capability to simulate the backend, allowing us to test and develop seamlessly.</p><h3>As a conclusion</h3><p>We have covered essential features of Postman that might be helpful when debugging the Network Layer. It allows every kinds of developer to send requests to APIs and inspect the responses. This is particularly useful for mobile developers who need to diagnose problems related to network requests in their apps.</p><p>I’m excited to connect with you in future articles. Until then, stay curious and keep learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc36b9fc9bfd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/debugging-chronicles-postman-for-network-debugging-cc36b9fc9bfd">Debugging Chronicles: Postman for Network Debugging</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging Chronicles: A Journey into View Layer Debugging Mastery]]></title>
            <link>https://medium.com/adessoturkey/debugging-chronicles-a-journey-into-view-layer-debugging-mastery-c642d299c5f2?source=rss-5ec2ef10956c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c642d299c5f2</guid>
            <dc:creator><![CDATA[İrem Tosun]]></dc:creator>
            <pubDate>Wed, 29 May 2024 13:49:07 GMT</pubDate>
            <atom:updated>2024-07-16T06:37:13.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*SdaASqF_CwbWIEHQJkBQNA.png" /></figure><p>Today, we’re going to explore some really awesome strategies as we delve into the interesting world of software debugging! I can assist you with everything, from understanding the complexities of SwiftUI when testing the view layer to <a href="https://medium.com/@iremgrel_38434/debugging-chronicles-exploring-breakpoints-conditions-lldp-commands-and-watchpoints-50987096dc3d">improving debugging skills</a>, and finally, experimenting with network layer debugging. So, take a seat comfortably and get ready to learn some awesome tips that will help you become a better debugger. There’s something here for every developer, regardless of experience level. You can download the<a href="https://github.com/iremgureltosun/Benchtime"> reference project</a> to experience more. Let’s get started and enjoy debugging! 🚀</p><blockquote>“Testing shows the presence, not the absence of bugs.” — Edsger W. Dijkstra</blockquote><p>Since SwiftUI is a declarative framework, you can’t add an imperative print call inside your view declaration. The reason is that the view body property expects to return a View value. To overcome that limitations while debugging your view, you can use one of several approaches depending on your needs.</p><p>To delve deeper into the topic and demonstrate how to use different approaches, I will provide you with some real code examples and screenshots from my sample app. In the meantime, I will also share my observations.</p><p>Now, I’ve designed a view with a visual bug. Let’s imagine you don’t know what caused the bug and you’re trying to fix it. I’ll show you how to use some runtime debugging methods to identify and resolve the problem with the SwiftUI view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*rKKWMg71oWyvapFry_8v7A.gif" /><figcaption>The problematic movements of vane is undetected.</figcaption></figure><p>If you look very carefully to the clock, you will notice that vane has an unexpected behaviour to move backwards frequently. In order to explore what caused this, you can use some of the techniques that I will provide.</p><p>In my example, this issue has occured because both timer in the view model and the animation on the view are making changes on the rotation angle of the vane. You can find all the details in the <a href="https://github.com/iremgureltosun/Benchtime">source code</a>. To spot the cause of the problem, you can debug the view.</p><h4><strong>1. Use LLDB Command</strong></h4><p>You can try to debug the issue with <em>let _ = Self._printChanges() </em>command. In order to do it, all you have to do is to add this command to the beginning of the body part of the view.</p><pre>struct AnimatedClockView: View {<br>    @State private var model: AnimationClockViewModel = .init()<br><br>    var body: some View {<br>        let _ = Self._printChanges()<br>        VStack {<br>            clock<br>        }<br>        .onAppear {<br>            model.startTimers()<br>            // Buggy field that moves the vane with a wrong angle<br>            withAnimation(.easeInOut(duration: 1).delay(8).repeatForever()) {<br>                model.rotate(type: .vane, angle: -10)<br>            }<br>        }<br>        .onDisappear {<br>            model.stopTimers()<br>        }<br>     }<br><br>                                    ...</pre><p>As a result of doing this, you will notice the following output on the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*u5KtFrMpOx23hWD43vUPvg.png" /></figure><p>As you see, it generated a line that explains why it is redrawn each time the model has changed.</p><p>Furthermore, If you are looking for a change in view after a specific action, you can also place a breakpoint to the start of the view and then type this lldb command to terminal: <strong>po Self._printChanges().</strong> This will also give you the reason why view has been redrawn.</p><h4><strong>2. Use of OnChange, onReceive Modifiers</strong></h4><p>The previous approach was indeed fantastic. However, it didn’t quite meet my needs. I require more detailed information to detect unexpected behavior. Therefore, I’d like to add this line to log the changes.</p><pre>.onChange(of: model.vaneRotationAngle, initial: false) { old, new in<br>   print(&quot;New rotation angle of vane was \(old) -&gt; now it is is \(new)&quot;)<br>}</pre><p>As you see, I am using the <em>onchange()</em> modifier of the view in order to debug the rotation angles, which give me the following output. You can also use onReceive, depending on your structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*wpGpIQe3ZmZazpIK3NqViA.png" /></figure><p>After observing more carefully, I can say that the unexpected angle occurs in the very beginning. Timer triggers the changes and changes are recognized each time. However, animations behave differently. Although I run it in a repeatForever mode, it is triggered just once. So with the help of this debugging, I can conclude that the timer causes this visual bug and it needs to be removed in order to fix the issue.</p><h4><strong>3. Take Advantage of Using View Extensions</strong></h4><p>Let’s talk about another scenario where you want to verify whether you are using the correct color as defined by the design team in your app. It is simple enough that you can add a View extension to accomplish this.</p><pre>extension View {<br>    func printOutput(_ value: Any, saying description: String = &quot;&quot;) -&gt; Self {<br>        let message = &quot;\(description) \(value)&quot;.trimmingCharacters(in: .whitespaces)<br>        print(message)<br>        return self<br>    }<br>}</pre><p>And then you can add the following function to your view:</p><pre>.printOutput(clockColor.hex, saying: &quot;Color hex code of the clock is&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*HXen2M7dPXsJdtU5ITr_sg.png" /><figcaption>As a result you will be able to debug the hex code.</figcaption></figure><p>Not limited to just colors or hex codes, you can debug every component in your view using this technique.</p><h4><strong>4. Use of Preview Provider</strong></h4><p>As you are already aware, SwiftUI has added a Canvas that greatly simplifies the lives of developers. Even though many developers neglect to spend a lot of attention on that functionality, the preview provider offers fantastic debugging methods.</p><p>Design is crucial, and SwiftUI is highly capable of producing responsive screens. However, we should invest more time in debugging to test all possible cases before publishing the app on the store.</p><p>First, <em>Select Editor-&gt; Canvas</em> from the menu bar. Then, select the Dynamic type variants from the third option.</p><h4>Dynamic Type Variants</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ccsGYTOr015jyEFmyqKXQw.png" /><figcaption>Selecting dynamic type variants</figcaption></figure><p>Please take a look at the unpolished design before debugging and adjusting my view using the preview provider. As you can see, there have been no adjustments made in my implementation for accessibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*TUrUCXyF8KuGuf8OsC9JYw.png" /><figcaption>Views displayed before making adjustments</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*4htukginFhwGKMLvx5k7uQ.png" /><figcaption>View gets unreadable when large appearence is preferred</figcaption></figure><p>For various accessibility options, font sizes are significantly increased to enhance readability for users who prefer larger fonts. Therefore, we may need to redesign components to accommodate all different type variants. Here’s an environment variable that can be a lifesaver for this purpose.</p><pre>@Environment(\.sizeCategory) var sizeCategory</pre><p>I used this variable to adjust my components and displayed the components differently based on their size category.</p><pre>VStack {<br>if sizeCategory &lt; ConstantSizeCategory.limit {<br>        MediumCharacterDetailView(viewModel: viewModel)<br>  } else {<br>        ExtraLargeCharacterDetailView(viewModel: viewModel)<br>  }<br>}</pre><pre>enum ConstantSizeCategory {<br>    static let limit: ContentSizeCategory = .extraLarge<br>}</pre><p>After making all the adjustments for a better design, I now feel more comfortable viewing the variants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*hQJL8WYkR0NZs_jBgUt1dQ.png" /><figcaption>Result of the display that is smaller than extra large category size.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*R7JXYUROfGsfzqwgqyR2Ig.png" /><figcaption>Improved design for large content sizes.</figcaption></figure><p>Apparently, the design changed completely for larger appearances. I made my own decisions while doing this. However, designers can offer much better designs for these kinds of improvements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*jqVDvtSoWIXxiH4B34GkMA.png" /><figcaption>Display for smaller variants.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*jRopE7yjnxVLv8C_uXINkA.png" /><figcaption>Display for larger variants.</figcaption></figure><h4>Color Scheme Variants</h4><p>Obviously, as the name suggests, you can also preview the dark mode and light mode appearances with the preview provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*nxly0aaQpdIfL6WCOHwiDg.png" /><figcaption>Preview of color scheme variants</figcaption></figure><p>You can also display it by clicking the run button, which is the first element of the button list. By selecting the dark appearance, you are good to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*gbzjifbzD0EPAfOF873NQA.png" /><figcaption>Displaying the dark appearence by using Canvas Device setting</figcaption></figure><h4>Orientation Variants</h4><p>Last but not least, orientation variants are also important since most of the apps support orientation of the device.</p><p>As you can see, with the help of this feature, we can notice a bug in the landscape orientation type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*HriGg2b0hnx96hOmeArs6A.png" /><figcaption>Spotted buggy look of landscape mode by preview provider.</figcaption></figure><p>By making a little adjustment in the width of the header view, we can fix this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFUFfms_T20pA95BTYwVUA.png" /><figcaption>Fixed version</figcaption></figure><p><strong>5. Debug View Hierarchy</strong></p><p>Let’s talk about the visual debugger. First and foremost, how do you access it? To access it, you need to set a breakpoint on the onAppear function in your SwiftUI View.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*7GDuiAdooyiGyo-36rS06g.png" /><figcaption>Setting breakpoint to the onAppear function.</figcaption></figure><p>As the execution pauses, if you look at the options available from this button, you will see an option that says “Debug View Hierarchy” when you hover over it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*NTTwj2ekxDxjVdR3s33MOg.png" /><figcaption>Toolbar displays debug view hierarchy option.</figcaption></figure><p>You can go ahead and click on it and you get brought into this cool view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AiBUDiL9QA0Nk3JvfPGs5Q.png" /><figcaption>You go into the visual debugger.</figcaption></figure><p>It actually pauses your app so you can’t interact with it right now. What you can do in here, on the right hand side, there is an “Object inspector” and “Size inspector” where you can observe all the constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*nXXevAH5ynoWSATT9tiJ-g.png" /><figcaption>Displaying size inspector.</figcaption></figure><p>Additionally, you can observe a specific component by right clicking and seeing the selections on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*vQLYADZ30eZG1hVmFjaHIw.png" /><figcaption>Possible options when you right click on a component.</figcaption></figure><p>Debugging view hierarchy comes in handy when you are programmatically creating you views. The UI debugger provides the developer with runtime constraint errors highlighted with purple ⚠️ symbol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5n2hSVqkwuU9FWlDQYabCA.png" /><figcaption>Some runtime errors are catched.</figcaption></figure><p>As you can see, it has already given me a few unexpected runtime issues. I’ll now dive into the code and tackle them immediately. 😊</p><p>We’ve explored various great methods for debugging SwiftUI applications’ view layer. I have another article where you can read <a href="https://medium.com/@iremgrel_38434/debugging-chronicles-exploring-breakpoints-conditions-lldp-commands-and-watchpoints-50987096dc3d">more about general debugging skills.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c642d299c5f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/debugging-chronicles-a-journey-into-view-layer-debugging-mastery-c642d299c5f2">Debugging Chronicles: A Journey into View Layer Debugging Mastery</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging Chronicles: Exploring Breakpoints, Conditions, LLDP Commands, and Watchpoints]]></title>
            <link>https://medium.com/adessoturkey/debugging-chronicles-exploring-breakpoints-conditions-lldp-commands-and-watchpoints-50987096dc3d?source=rss-5ec2ef10956c------2</link>
            <guid isPermaLink="false">https://medium.com/p/50987096dc3d</guid>
            <dc:creator><![CDATA[İrem Tosun]]></dc:creator>
            <pubDate>Wed, 29 May 2024 13:48:29 GMT</pubDate>
            <atom:updated>2024-07-16T06:37:22.648Z</atom:updated>
            <content:encoded><![CDATA[<h3>Debugging Chronicles: Exploring Breakpoints, Conditions, LLDB Commands, and Watchpoints</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhdoqN7rQngZj6CuCdH5lg.png" /></figure><p>When it comes to creating a product, the business layer is as crucial as the design. Now that we’ve seen <a href="https://medium.com/@iremgrel_38434/debugging-chronicles-a-journey-into-view-layer-debugging-mastery-c642d299c5f2">how to debug view components</a>, we can talk about debugging anything, especially the business logic.</p><p><strong>Using Playground files</strong></p><p>In most projects, there certainly needs to be some helper functions. If those functions are buggy, your app or a feature of your app will not work as expected. So, I recommend debugging/testing your helper functions, especially the ones that include complex business logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*9Ia48hJuIDMdJFnRmBvEtA.png" /><figcaption>Testing some functions with the playground file.</figcaption></figure><p>You can simply add playground file into your project. All you need to do is to insert a new file from menu bar: <em>File-&gt; New-&gt; Playground</em></p><p>Please keep in mind that if the playground file and the models called inside are in the same module, it won’t be a problem. Otherwise, you need to give public access level to your models in order to use them.</p><h4>Use of Breakpoints</h4><p>As a developer, I can’t imagine implementing complex features or fixing bugs without breakpoints. A breakpoint is a debugging tool that allows you to pause the execution of your program at a certain moment. Breakpoints in Xcode are essential tools for effectively debugging code.</p><p>Just click on the bottom area adjacent to the code line you wish to pause in order to establish a breakpoint. Run your application in debug mode after setting the breakpoint, and it will stop when it reaches it. From there, you can rapidly identify and address problems in your code by using Xcode’s debugging features, which include the debug console, variable inspection, and step-through execution. Breakpoints are customizable and can be turned on and off to meet your debugging requirements.</p><h4>Use of LLDB Commands</h4><p>During debugging sessions, Xcode’s LLDB (Low-Level Debugger) debugger offers an extensive command set for <strong>examining</strong> and <strong>modifying</strong> the state of your program in addition to allowing you to set breakpoints.</p><p>LLDB commands are somehow related to breakpoints, as you cannot run an LLDB command in the terminal without first placing a breakpoint.</p><p><strong>Inspecting Your Code: Essential LLDB Commands to Examine</strong></p><p><strong>p Command</strong></p><p>p<strong>(print)</strong>, a basic LLDB command, lets you print a variable’s value in the debug console. For instance, entering p<strong> url</strong> will cause the url variable to print its current value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*uEJ6qCon2DAxsQsoT44WAQ.png" /><figcaption>Observing the variable with p command.</figcaption></figure><p><strong>po Command</strong></p><p>Another command similar to p is po. The po command will similarly print your object with all of its properties to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wkHsbfUsp38tFa4aC2lAGQ.png" /><figcaption>Observing the object with po command.</figcaption></figure><p><strong>e Command</strong><br>The e command represents expression and is used for analyzing it. It is capable of executing any code in the current environment of the currently selected frame. This means you may use functions, assign values, and carry out other operations the way you would if you generated code in your source files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*g1Kl7YxWfaXjcsfWIm3Omw.png" /><figcaption>Debugging the makeUrlString function with e command.</figcaption></figure><h4>Use LLDB Commands for Modification on Run Time</h4><p>Actually, the fundamental goal of utilizing the LLDB command for modification is to leave things unaltered.</p><p><strong>p Command for Modification</strong></p><p>The p command allows you to edit variables and run code within the context of the current debugging session. Here’s how you can edit variables with the p command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*G0s4agBJRwzujKQu9ngqrw.png" /><figcaption>Using p command for modifying the name of the person.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*3ucoAPe-KMr6FP_6aptdZA.png" /><figcaption>Screen before running p Command.</figcaption></figure><p>I absolutely haven’t made any changes in the implementation. Just ran p command for modification and I can see the difference on the screen afterwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*XQHYRfWroim2DdrOaJDK0w.png" /><figcaption>After running the p command for modification, I have the value that I want to display for testing.</figcaption></figure><p><strong>e Command for Modification</strong></p><p>You can use e command and test a function during runtime without making any changes in the implementation as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*vLYuNoLxeUT0LsI8hgme-g.png" /><figcaption>Running e command for altering a variable.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*tKyu3GWuaJxwrTBGURj4zw.png" /><figcaption>Previously, my query result variable is empty before running the command.</figcaption></figure><p>After running the command, the variable changed successfully. I wasn’t supposed to change anything inside the testButton() function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*uFA80kdSxu6oVL0ZnttIxQ.png" /><figcaption>The function was mocked somehow, giving me the updated value as needed.</figcaption></figure><p>As a conclusion, LLDB’s ability to modify variables in real-time enables dynamic adjustments to the behavior of your program, which can be especially useful when fine-tuning algorithms or experimenting with different configurations. By altering variables directly in the debugger, you can iterate more rapidly on your debugging process, refining your understanding of the problem and testing potential solutions iteratively.</p><h4>Conditional Breakpoints</h4><p>With Xcode’s advanced debugging capability, you may interrupt program execution only when specific criteria are satisfied by using a conditional breakpoint. This makes it easier to find and repair flaws in your code, especially when you want to look at issues that arise under particular conditions.</p><p>To set a conditional breakpoint, open the breakpoint inspector. Right-click on the blue breakpoint indicator. Select <strong>Edit Breakpoint </strong>from the context menu. This will open the Breakpoint Inspector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*78ow_jcgv4DRN5U4dW84UQ.png" /><figcaption>Adding the condition with breakpoint inspector.</figcaption></figure><p>I have used this functionality to ensure that the pull functionality works as expected. The record count is initially 20, and to understand that pagination works, the record count must be greater than 20. I preferred to log a message in that case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*1GyABwUBwiS3OcLROgytIQ.png" /><figcaption>As a pull to get more records, conditional breakpoint worked and I saw a log message on the terminal.</figcaption></figure><p>Let’s be more compelling and edit this breakpoint to pause after ignoring 2 attempts. In this way, I am testing if I get at least 80 records after pagination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*3nqTMQ9g2lB3E86UH6OoIw.png" /><figcaption>Adding more conditions to breakpoint.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*-_q5udAvRl04SrKemLRUjQ.png" /><figcaption>I can see that it works as expected.</figcaption></figure><p>Well, that functions as expected. As you can see, I verified that my pagination works as expected by using the conditional breakpoint. It is your call to use it in any way you need.</p><p>Obviously, it doesn’t only provide logging functionality. You can also run some debugger commands depending on a condition. In the screenshot below, when my search functionality runs, I have searched for ‘Morty’ when the user entered an empty string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*ft-EL72hkwtqK96avHRRVg.png" /><figcaption>Used conditional breakpoint and a debugger command.</figcaption></figure><h4>Add a WatchPoint</h4><p>Instead of stopping the program’s execution when a line of code is encountered, watchpoints function similarly to breakpoints. Instead, when a particular variable’s value changes, they suspend the program. In situations where you are uncertain about the location or timing of a variable’s value alteration within your code, this capability becomes extremely handy.</p><p>In order to add a watchpoint to a variable, we need to add a breakpoint at first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*LIBUXsld_RBPp-x6cLg-hg.png" /><figcaption>I want to watch the changes in vane rotation angle.</figcaption></figure><p>I simply right-click on the variable that I want to watch. I continue execution, and the execution pauses whenever the watched variable changes. This allows me to inspect the new value and see exactly where in the code the change has occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*Y7iOz-uGldAkhPuy5vuaIg.png" /><figcaption>Output of changes in the terminal.</figcaption></figure><p>Thank you for joining me on this deep dive into the world of debugging with breakpoints, conditions, LLDB commands, and watchpoints. Mastering these tools and techniques is crucial for efficient and effective software development. I hope this exploration has provided you with valuable insights and practical tips to enhance your debugging skills. Remember, debugging is an art, and the more you practice, the more proficient you’ll become. Happy debugging, and until next time, keep solving those challenging bugs with confidence and precision!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50987096dc3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/debugging-chronicles-exploring-breakpoints-conditions-lldp-commands-and-watchpoints-50987096dc3d">Debugging Chronicles: Exploring Breakpoints, Conditions, LLDP Commands, and Watchpoints</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing Versatile Storage Solutions with Dependency Injection]]></title>
            <link>https://medium.com/adessoturkey/use-of-dependency-injection-with-swiftdata-06b20811eb43?source=rss-5ec2ef10956c------2</link>
            <guid isPermaLink="false">https://medium.com/p/06b20811eb43</guid>
            <dc:creator><![CDATA[İrem Tosun]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 08:17:30 GMT</pubDate>
            <atom:updated>2024-05-29T08:15:50.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOtckKZ9GSogxVIwbvtiww.png" /></figure><p>If you enter “Swift Data” in the Google search bar, you’ll find numerous useful examples. Many of these examples involve injecting a container from the app file and using the @Query macro, along with injecting model context directly into the view in SwiftUI projects.</p><p>In this article, my goal is to demonstrate a different approach: isolating the persistence layer from views and view models while adhering to the MVVM pattern. The main point I want to convey is that accessing property wrappers from the view is exceedingly easy and effortless. However, by opting for the simpler approach, you’ll miss the opportunity to implement unit tests, resulting in a less flexible application.</p><p>If you’re ready, we can dive deeper into the topic with sample code snippets from my <a href="https://github.com/iremgureltosun/ReminderAppSwiftUI">sample app</a>. I’ve made an effort to keep this app as simple as possible while focusing mainly on the architecture to provide fully isolated layers.</p><p>Dependency Injection (DI) is like organizing your tools in a toolbox to make things easier. It helps keep things simple and organized when you’re working on a project. This architecture allows me to:</p><ul><li>Use the MVVM pattern</li><li>Write unit tests simply by injecting the persistence layer.</li><li>Use different storage techniques within the same project without needing to spend extra effort on refactoring.</li></ul><p>First, let’s take a look at the place where the app launches:</p><pre>@main<br>struct RemindMeApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            NavigationStack {<br>                ContentView()<br>            }<br>        }<br>    }<br>}</pre><p>I haven’t done anything specific for SwiftData in that part. Since the primary objective is to store all data-related aspects in the persistence layer, there’s no necessity to include anything related to SwiftData in common views or models.</p><p>I’ve chosen to use Swinject for dependency injection. You can opt for any other framework or implement it independently, as the logic and approach remain consistent. The initial step involves implementing a Resolver and ContainerBuilder for dependency injection.</p><p>To inject the relevant layer into my view models, I need to use both of these functions. I’m in the process of creating a property wrapper. In Swift, a property wrapper is a type that lets you encapsulate property access within a defined set of behaviors. It offers a straightforward approach to streamlining the common code for managing the state or behavior of properties.</p><pre><br>@propertyWrapper<br>@MainActor<br>struct Inject&lt;Component&gt; {<br>    let wrappedValue: Component<br>    init() {<br>        wrappedValue = Resolver.shared.resolve(Component.self)<br>    }<br>}</pre><p>As you see, using the MVVM pattern, I am able to inject the persistence layer into the viewModel like below:</p><pre>import Foundation<br><br>final class ListLectureViewModel: BasePersistentViewModel {<br>    @Published var list: [Lecture] = []<br>    @Inject var storageManager: LectureStorageProtocol<br>    @Published var itemToEdit: Lecture?<br><br>    func loadItems() {<br>        do {<br>            list = try storageManager.fetch()<br>        } catch {<br>            list = []<br>        }<br>    }<br><br>    func delete(_ item: Lecture) throws {<br>        try storageManager.delete(item)<br>    }<br>}</pre><p>Secondly, I am able to test functions of persistence layer with unit tests.</p><pre>@testable import RemindMe<br>import XCTest<br><br>final class LecturePersistenceManagerTests: XCTestCase {<br>    @Inject var  lectureManager: LectureStorageProtocol<br><br>    func testInsert() {<br>        let lecture = Lecture(id: UUID().uuidString, title: &quot;History&quot;, subtitle: &quot;Atatürk İlke ve Inkılapları&quot;)<br>        do {<br>            try lectureManager.save(lecture)<br>            let recordFromDb = try lectureManager.fetch().filter { $0.id == lecture.id }.first<br>            XCTAssertTrue(recordFromDb == lecture)<br>        } catch {<br>            XCTFail(&quot;Error occured \(error)&quot;)<br>        }<br>    }<br>}</pre><p>Lastly, it’s worth noting that I retain the flexibility to switch storage techniques without needing to modify my view models, views, or unit tests. I’ve designed this implementation to showcase the adaptability of dependency injection. It’s important to understand that you don’t necessarily need to employ two different types of databases in your own project; this approach demonstrates the versatility of the design.</p><pre>import Foundation<br>import Swinject<br><br>@MainActor<br>final class Resolver {<br>    private var container: Container<br>    static let shared = Resolver()<br>    private init() {<br>        if #available(iOS 17.0, *) {<br>            container = SwiftDataContainerBuilder.shared.buildContainer()<br>        } else {<br>            container = RealmContainerBuilder.shared.buildContainer()<br>        }<br>    }<br>    func resolve&lt;T&gt;(_: T.Type) -&gt; T {<br>        container.resolve(T.self)!<br>    }<br>}</pre><h3><strong>Below the Surface</strong></h3><p>To achieve the mentioned flexibility in this project, I need the following components:</p><h4><strong>Common Models (Isolated from Storage Frameworks)</strong>:</h4><p>I have created models (data structures) that are not tied to any specific storage framework. These models represent the common data structures used in this application and are independent of the storage mechanisms.</p><pre>class Lecture: CommonModelProtocol, ObservableObject, Identifiable, Hashable {<br>    var id: String<br>    var title: String = &quot;&quot;<br>    var subtitle: String = &quot;&quot;<br>    init(id: String, title: String, subtitle: String) {<br>        self.id = id<br>        self.title = title<br>        self.subtitle = subtitle<br>    }<br>    static func == (lhs: Lecture, rhs: Lecture) -&gt; Bool {<br>        return lhs.id == rhs.id<br>    }<br>    func hash(into hasher: inout Hasher) {<br>        hasher.combine(id)<br>    }<br>}</pre><h4><strong>Protocols (Isolated from Storage Frameworks)</strong>:</h4><p>I have established protocols that abstract storage-related operations, encompassing essential functions such as saving, retrieving, updating, and deleting data. The models employed within these protocols are intentionally decoupled from any particular storage framework. This deliberate separation enables me to achieve a high degree of isolation from the underlying storage implementation.</p><pre>// MARK: All the isolated models are conforming to CommonModelProtocol <br>public protocol CommonModelProtocol {<br>    var title: String { get }<br>}<br><br>// MARK: LectureStorageProtocol provides isolation<br>protocol LectureStorageProtocol {<br>    func save(_ model: Lecture) throws<br>    func fetch() throws -&gt; [Lecture]<br>    func delete(_ model: Lecture) throws<br>}<br><br>// MARK: StorageProtocol helps me to convert isolated models to required storage models.<br>public protocol StorageProtocol {<br>    associatedtype EntityType<br>    init(_ entity: EntityType)<br>    func getModel() -&gt; EntityType<br>}<br><br>// MARK: ManagerProtocol provides generic integration<br>protocol ManagerProtocol {<br>    associatedtype EntityType: CommonModelProtocol<br>}</pre><h4><strong>Models with Storage Requirements</strong>:</h4><p>I have defined models that conform to the protocols mentioned earlier. These models will have the necessary implementations to work with the chosen storage frameworks, adhering to the defined protocols.</p><p>In the code block below, you see the model required for Realm.</p><pre>import Foundation<br>import RealmSwift<br><br>class LectureRealmModel: Object, StorageProtocol {<br>    typealias EntityType = Lecture<br>    @Persisted(primaryKey: true) var id: String<br>    @Persisted var title: String = &quot;&quot;<br>    @Persisted var subtitle: String = &quot;&quot;<br>    override static func primaryKey() -&gt; String? {<br>        return &quot;id&quot;<br>    }<br>    convenience init(id: String, title: String, subtitle: String) {<br>        self.init()<br>        self.id = id<br>        self.title = title<br>        self.subtitle = subtitle<br>    }<br>    required init(_ entity: Lecture) {<br>        super.init()<br>        id = entity.id<br>        title = entity.title<br>        subtitle = entity.subtitle<br>    }<br>    func getModel() -&gt; Lecture {<br>        return Lecture(id: id, title: title, subtitle: subtitle)<br>    }<br>}</pre><p>And, in the one below you see the model required for SwiftData</p><pre>import SwiftData<br><br>@available(iOS 17, *)<br>@Model class LecturePersistentModel: Identifiable, Hashable, StorageProtocol {<br>    typealias EntityType = Lecture<br>    @Attribute(.unique) public var id: String<br>    public var title: String<br>    var subtitle: String<br>    required init(_ entity: Lecture) {<br>        id = entity.id<br>        title = entity.title<br>        subtitle = entity.subtitle<br>    }<br>    init(id: String, title: String, subtitle: String) {<br>        self.id = id<br>        self.title = title<br>        self.subtitle = subtitle<br>    }<br>    func getModel() -&gt; Lecture {<br>        return Lecture(id: id, title: title, subtitle: subtitle)<br>    }<br>}</pre><h4><strong>Storage Services of Storage Frameworks</strong>:</h4><p>I have implemented concrete storage services based on the protocols. These services will utilize the storage frameworks (SwiftData and Realm) to fulfill the storage requirements defined in the protocols.</p><h4><strong>Base Concrete Class for Realm:</strong></h4><pre>import Foundation<br>import RealmSwift<br><br>@MainActor<br>class BaseRealmManager&lt;T&gt;: ManagerProtocol where T: StorageProtocol, T: Object, T.EntityType: CommonModelProtocol {<br>    typealias EntityType = T.EntityType<br>    private var items: [EntityType] = []<br>    init() {}<br>    func save(_ model: EntityType) throws {<br>        let realm = try Realm()<br>        try realm.write {<br>            realm.add(T(model))<br>        }<br>    }<br>    func fetch() throws -&gt; [EntityType] {<br>        let realm = try Realm()<br>        let objects = realm.objects(T.self)<br>        return objects.map { $0.getModel() }<br>    }<br>    func delete(_ model: EntityType) throws {<br>        let realm = try Realm()<br>        guard let modelObject = model as? Object else {<br>            throw PersistenceError.realmError<br>        }<br>        guard modelObject.realm != nil else {<br>            throw PersistenceError.realmError<br>        }<br>        do {<br>            try realm.write {<br>                realm.delete(modelObject)<br>            }<br>        } catch {<br>            throw PersistenceError.realmError<br>        }<br>    }<br>}</pre><p>I have a BaseRealmManager; that class uses a generic type, denoted as T, and it specifies that T should have certain features:</p><ul><li>It should conform to the StorageProtocol.</li><li>It should be a Realm object (conform to Object).</li><li>It should have a nested type called EntityType that conforms to CommonModelProtocol.</li></ul><pre><br>final class LectureRealmManager: BaseRealmManager&lt;LectureRealmModel&gt;, LectureStorageProtocol {}</pre><h4><strong>Base Concrete Class for SwiftData:</strong></h4><p>I have a BasePersistenceManager; that class uses a generic type, denoted as T, and it specifies that T should have certain features:</p><ul><li>It should conform to the StorageProtocol.</li><li>It should be a PersistentModel.</li><li>It should have a nested type called EntityType that conforms to CommonModelProtocol.</li></ul><pre>import Foundation<br>import SwiftData<br><br>@available(iOS 17, *)<br>@MainActor<br>class BasePersistenceManager&lt;T&gt;: ManagerProtocol where T: StorageProtocol, T: PersistentModel, T.EntityType: CommonModelProtocol {<br>    typealias EntityType = T.EntityType<br>    let context: ModelContext<br>    init(context: ModelContext) {<br>        self.context = context<br>    }<br>    private var items: [EntityType] = []<br>    func save(_ model: EntityType) throws {<br>        context.insert(T(model))<br>        try context.save()<br>    }<br>    func fetch() throws -&gt; [EntityType] {<br>        let descriptor = FetchDescriptor&lt;T&gt;() // (sortBy: [SortDescriptor(\.title)])<br>        let dbitems = try context.fetch(descriptor)<br>        items = dbitems.map { $0.getModel() }<br>        return items<br>    }<br>    func delete(_ model: EntityType) throws {<br>        context.delete(T(model))<br>        try context.save()<br>    }<br>}</pre><pre><br>@available(iOS 17, *)<br>final class LecturePersistenceManager: BasePersistenceManager&lt;LecturePersistentModel&gt;, LectureStorageProtocol {}</pre><p>On both of these options, base class provides methods for saving, fetching, and deleting data of the specified type. The EntityType alias simplifies the use of the nested type for the specific T you use when creating an instance of the class.</p><h3>The Heart and Soul</h3><p>To establish proper dependency injection, it’s essential to implement container builders that facilitate the resolution of dependencies.</p><pre>import Foundation<br>import SwiftData<br>import Swinject<br><br>@available(iOS 17, *)<br>@MainActor<br>final class SwiftDataContainerBuilder {<br>    static let shared = SwiftDataContainerBuilder()<br><br>    <br>    private var modelContainer: ModelContainer<br><br>    private init() {<br>        modelContainer = try! ModelContainer(for: LecturePersistentModel.self, StudentPersistentModel.self, SchoolPersistentModel.self, configurations: ModelConfiguration(isStoredInMemoryOnly: false))<br>    }<br><br>    private lazy var context: ModelContext = {<br>        return modelContainer.mainContext<br>    }()<br><br>    func buildContainer() -&gt; Container {<br>        let container = Container()<br><br>        container.register(LectureStorageProtocol.self) { _ in<br>            LecturePersistenceManager(context: self.context)<br>        }.inObjectScope(.container)<br><br>        container.register(StudentStorageProtocol.self) { _ in<br>            StudentPersistenceManager(context: self.context)<br>        }.inObjectScope(.container)<br><br>        container.register(SchoolStorageProtocol.self) { _ in<br>            SchoolPersistenceManager(context: self.context)<br>        }.inObjectScope(.container)<br><br>        return container<br>    }<br>}</pre><pre>import Foundation<br>import Swinject<br><br>@MainActor<br>final class RealmContainerBuilder {<br>    static let shared = RealmContainerBuilder()<br><br>    func buildContainer() -&gt; Container {<br>        let container = Container()<br><br>        container.register(LectureStorageProtocol.self) { _ in<br>            LectureRealmManager()<br>        }.inObjectScope(.container)<br><br>        container.register(StudentStorageProtocol.self) { _ in<br>            StudentRealmManager()<br>        }.inObjectScope(.container)<br><br>        container.register(SchoolStorageProtocol.self) { _ in<br>            SchoolRealmManager()<br>        }.inObjectScope(.container)<br><br>        return container<br>    }<br>}</pre><h3>Summing It Up in a Nutshell</h3><p>I have established a generic structure that allows seamless integration between the common models, protocols, models with storage requirements, and storage services. Dependency injection can be a key aspect of this structure, allowing for easy swapping of implementations and providing the desired flexibility.</p><p>By having these components in place, we can achieve a modular and flexible architecture that enables you to switch between storage frameworks or techniques without tightly coupling your application to a specific implementation. This approach promotes maintainability, testability, and adaptability to changing requirements or technologies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06b20811eb43" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/use-of-dependency-injection-with-swiftdata-06b20811eb43">Unleashing Versatile Storage Solutions with Dependency Injection</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Firebase: Push Notifications and Beyond]]></title>
            <link>https://medium.com/adessoturkey/use-of-firebase-for-chat-and-push-notifications-4ebe38d265cc?source=rss-5ec2ef10956c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ebe38d265cc</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[firebaseauthentication]]></category>
            <category><![CDATA[fcm-push-notification]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[İrem Tosun]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 12:07:19 GMT</pubDate>
            <atom:updated>2023-10-26T08:39:30.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hXvVtcE1fKJc1MMEdVmdEA.jpeg" /></figure><p>Today, I’m going to demonstrate how you can create a <a href="https://github.com/iremgureltosun/mini_chat_app">simple chat application</a> using Firebase tools within SwiftUI. This app will have chat rooms where users can engage in conversations and share pictures within user groups. Additionally, the app will be capable of receiving notifications from Firebase to keep you notified. In the first part of this article, I will mainly focus on the use of FirebaseStore and FirebaseAuth.</p><p>Please remember that <a href="https://github.com/iremgureltosun/mini_chat_app">this sample app</a> won’t run immediately after you download it to your local machine. You’ll need to set up your own GoogleService-info.plist file on your local setup to run this application.</p><h3><strong>PART 1. Using FirebaseStorage, FirebaseFirestore and FirebaseAuth</strong></h3><ol><li><strong>Firebase Configuration and Initialization:</strong></li></ol><blockquote>FirebaseFirestore is a real-time cloud database service that enables developers to store, sync, and query data for their apps. <a href="https://firebase.google.com/docs?hl=tr">Firebase Documentation</a></blockquote><p>To get started with the amazing features offered by Firebase, begin with logging into the Firebase Console. This is where you can set up and configure all the necessary components for your project.</p><p>Firstly, navigate to the <a href="https://console.firebase.google.com/">Firebase Console</a>, where you’ll need to login and initiate a new project for your application. Once this step is complete, Firebase will furnish you with a plist file named GoogleServices.plist. You must integrate this GoogleServices.plist file into your app. Subsequently, proceed to create an AppDelegate file within your SwiftUI project.</p><p>In SwiftUI projects, the conventional usage of the AppDelegate is somewhat diminished. This is due to SwiftUI’s internal management of the app’s lifecycle, facilitated by the @main App protocol and the @UIApplicationDelegateAdaptor attribute. Nevertheless, in some cases, it is necessary to employ the AppDelegate, particularly when incorporating external frameworks such as Firebase, which rely on the traditional UIApplicationDelegate methods.</p><p>Firebase requires configuration and initialization when the app launches. This involves setting up services like Firebase Cloud Messaging, Authentication, Realtime Database, etc. While SwiftUI’s App protocol provides lifecycle management, Firebase often relies on traditional <strong>UIApplicationDelegate</strong> methods to initialize itself when the app starts. This is where the <strong>AppDelegate</strong> comes in.</p><p>FirebaseApp.configure():</p><p>The AppDelegate is used to call <strong>FirebaseApp.configure()</strong> in the <strong>application(_:didFinishLaunchingWithOptions:)</strong> method. This method is automatically called when the app is launched. <strong>FirebaseApp.configure()</strong> initializes the Firebase services based on the configurations you’ve set up in the Firebase Console.</p><p><strong>2. Using Authentication Methods of FirebaseAuth</strong></p><blockquote>FirebaseAuth is a service that provides developers with authentication, allowing users to securely sign in to apps using various methods like email/password or social identity providers. <a href="https://firebase.google.com/docs?hl=tr">Firebase Documentation</a></blockquote><p>Now that we’ve completed all the required tasks within the AppDelegate for the first part, it’s time to leverage the capabilities of our chat application. Through Firebase Authentication, users can effortlessly log in and register for the app. As demonstrated in the following code block, we simply invoke two concurrent functions provided by the FirebaseAuth framework.</p><pre>private func login() async {<br>        do {<br>            let _ = try await Auth.auth().signIn(withEmail: email, password: password)<br>            appManager.routes.append(.chat)<br>        } catch {<br>            errorMessage = error.localizedDescription<br>        }<br>    }<br><br>private func signUp() async {<br>        do {<br>            let result = try await Auth.auth().createUser(withEmail: email, password: password)<br>            try await userManager.updateDisplayName(for: result.user, displayName: displayName)<br>            // Activate login view<br>            presentLogin = true<br>        } catch {<br>            appManager.errorWrapper = ErrorWrapper(error: error, guidance: error.localizedDescription)<br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*L4wnb3zcojgewWpKhWt-QA.png" /></figure><p>As shown in the screenshot, you can set up the rules for your FireStore database. In this sample app, I’ve decided to make sure users are signed in. But don’t worry; you can change these rules to match your own preferences. This lets you control who can access your database and how it’s protected.</p><p><strong>2. Creating Database Models</strong></p><p>Next, we’re going to talk about something really important: creating the structures for our database. If you know about setting up code-first databases, this will make sense. With Firebase, the database fields are kind of built automatically from what you design. Please keep in mind that if you make changes to your model, the data you had before will stay in the cloud, but you won’t be able to reach that older data.</p><p>I’ve designed my chat messages to be organized within chat groups. When a user sends a chat message to any group, that message gets stored within the data of that specific group.</p><pre>struct ChatGroup: Codable, Identifiable {<br>    var documentId: String? = nil<br>    let subject: String<br><br>    var id: String {<br>        documentId ?? UUID().uuidString<br>    }<br>}<br>extension ChatGroup {<br>    func toDictionary() -&gt; [String: Any] {<br>        return [DBCollections.ChatGroup.subject: subject]<br>    }<br><br>    static func fromSnapshot(snapshot: QueryDocumentSnapshot) -&gt; ChatGroup? {<br>        let dictionary = snapshot.data()<br>        guard let subject = dictionary[DBCollections.ChatGroup.subject] as? String else {<br>            return nil<br>        }<br><br>        return ChatGroup(documentId: snapshot.documentID, subject: subject)<br>    }<br>}<br><br>struct ChatMessage: Codable, Identifiable, Equatable {<br>    var messageOwnerIsMe: Bool {<br>        guard let loggedInUserId = Auth.auth().currentUser?.uid else { return false }<br>        return uid == loggedInUserId<br>    }<br><br>    var documentId: String?<br>    let text: String<br>    let uid: String<br>    var dateCreated = Date()<br>    let displayName: String<br>    var profilePhotoURL: String = &quot;&quot;<br>    var attachmentPhotoURL: String = &quot;&quot;<br><br>    var id: String {<br>        documentId ?? UUID().uuidString<br>    }<br><br>    var displayProfilPhotoURL: URL? {<br>        profilePhotoURL.isEmpty ? nil : URL(string: profilePhotoURL)<br>    }<br><br>    var displayAttachmentPhotoURL: URL? {<br>        attachmentPhotoURL.isEmpty ? nil : URL(string: attachmentPhotoURL)<br>    }<br>}<br>extension ChatMessage {<br>    func toDictionary() -&gt; [String: Any] {<br>        return [<br>            DBCollections.ChatMessage.text : text,<br>            DBCollections.ChatMessage.uid : uid,<br>            DBCollections.ChatMessage.dateCreated : dateCreated,<br>            DBCollections.ChatMessage.displayName : displayName,<br>            DBCollections.ChatMessage.profilePhotoURL : profilePhotoURL,<br>            DBCollections.ChatMessage.attachmentPhotoURL : attachmentPhotoURL,<br>        ]<br>    }<br><br>    static func fromSnapshot(snapshot: QueryDocumentSnapshot) -&gt; ChatMessage? {<br>        let dictionary = snapshot.data()<br>        guard let text = dictionary[DBCollections.ChatMessage.text] as? String,<br>              let uid = dictionary[DBCollections.ChatMessage.uid] as? String,<br>              let dateCreated = (dictionary[DBCollections.ChatMessage.dateCreated] as? Timestamp)?.dateValue(),<br>              let displayName = dictionary[DBCollections.ChatMessage.displayName] as? String,<br>              let profilePhotoURL = dictionary[DBCollections.ChatMessage.profilePhotoURL] as? String,<br>              let attachmentPhotoURL = dictionary[DBCollections.ChatMessage.attachmentPhotoURL] as? String<br>        else {<br>            return nil<br>        }<br><br>        return ChatMessage(documentId: snapshot.documentID, text: text, uid: uid, dateCreated: dateCreated, displayName: displayName, profilePhotoURL: profilePhotoURL, attachmentPhotoURL: attachmentPhotoURL)<br>    }<br>}</pre><p>As you can see from the model above, I’ve structured my chat message model this way. The method named toDictionary() transforms the object into a dictionary format for storage on Firebase. On the other hand, the second method called fromSnapshot(snapshot: QueryDocumentSnapshot) is crucial for retrieving data from Firebase. I’ve chosen to use constant strings to ensure consistency in this process.</p><p><strong>2. Data Manipulation</strong></p><p>Now, it is time to read and write to our database. This <strong>GroupsManager</strong> class acts as a bridge between our SwiftUI views and the Firebase Firestore database. It provides methods to send messages, listen for new messages, and detach the listener when necessary.</p><ul><li>db is an instance of Firestore, which is the primary Firebase service for cloud-hosted databases.</li><li>collection is a CollectionReference that represents a specific Firestore collection used for managing chat groups.</li><li>The listenChatMessages method listens for new chat messages in a particular chat group. It clears the chatMessages array and establishes a Firestore snapshot listener to monitor changes in the message collection of the chat group. When new messages are added to the collection, the listener responds by appending them to the chatMessages array.</li><li>We’re using Firestore’s addDocument function to store message data within the messages collection of the chat group.</li><li>The detachFirebaseListener method is called when the page disappears.</li></ul><pre>@MainActor<br>class GroupsManager: ObservableObject {<br>    @Published var chatRooms: [ChatGroup] = []<br>    @Published var chatMessages: [ChatMessage] = []<br><br>    let db = Firestore.firestore()<br>    let collection: CollectionReference<br>    var firestoreListener: ListenerRegistration?<br><br>    init() {<br>        collection = db.collection(DBCollections.groups)<br>    }<br><br>    func sendMessage(message: ChatMessage, chatRoom: ChatGroup) async throws {<br>        guard let roomDocumentId = chatRoom.documentId else { return }<br>        try await collection.document(roomDocumentId)<br>            .collection(DBCollections.messages)<br>            .addDocument(data: message.toDictionary())<br>    }<br><br>    func listenChatMessages(in chatRoom: ChatGroup) async throws {<br>        chatMessages.removeAll()<br>        guard let documentId = chatRoom.documentId else { return }<br>        firestoreListener = db.collection(DBCollections.groups)<br>            .document(documentId)<br>            .collection(DBCollections.messages)<br>            .order(by: &quot;dateCreated&quot;, descending: false)<br>            .addSnapshotListener { [weak self] snapshot, _ in<br>                guard let snapshot = snapshot else {<br>                    print(&quot;Error fetching snapshot&quot;)<br>                    return<br>                }<br>                snapshot.documentChanges.forEach { change in<br>                    if change.type == .added {<br>                        if let message = ChatMessage.fromSnapshot(snapshot: change.document) {<br>                            self?.chatMessages.append(message)<br>                        }<br>                    }<br>                }<br>            }<br>    }<br><br>    func detachFirebaseListener() {<br>        firestoreListener?.remove()<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fA47xGw98A__CFUtTx45Ww.png" /></figure><p>This is how it appears in the cloud. Would you be interested in seeing how conversations in the chat room are presented within the app? Here we go! :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8m1IYmJ1oHeXO1u0cTYIow.png" /></figure><p>In the project files, you will discover a variety of implementations that include additional details you might require for a chat app. However, in this article, I am focusing solely on utilizing the most crucial code blocks to explain Firebase usage.</p><p>3. <strong>Image Storage</strong></p><p>In Firebase, images are stored in the Storage section. Please remember that resizing images before uploading them to the server is a very useful approach.</p><pre> private func sendMessage() async throws {<br>        guard let user = Auth.auth().currentUser else { return }<br>        var chatMessage = ChatMessage(documentId: UUID().uuidString, text: dialogConfig.chatText, uid: user.uid, dateCreated: Date(), displayName: user.displayName ?? StaticKeywords.guest, profilePhotoURL: user.photoURL?.absoluteString ?? &quot;&quot;)<br>        // If user selects an image, we add attachment to message!<br>        if let selectedImage = dialogConfig.selectedImage {<br>            let resizedImage = selectedImage.aspectFittedToHeight(300)<br>            guard let imageData = resizedImage.pngData() else { return }<br><br>            let url = try await Storage.storage().uploadData(for: UUID().uuidString, data: imageData, bucket: .attachments)<br>            chatMessage.attachmentPhotoURL = url.absoluteString<br>        }<br>        appManager.loadingState = .loading(&quot;Uploading image&quot;)<br><br>        try await chatManager.sendMessage(message: chatMessage, chatRoom: chatRoom)<br>        appManager.loadingState = .idle<br>        clearFields()<br>    }</pre><p>And this is what attached image files look like on the cloud:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6CePKqSFoSU7Y72zezlXw.png" /><figcaption>We have stored two different types of images in Storage.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQDpC4nqP2rZMNOVnc-Q0Q.png" /><figcaption>You can access each attachment from the console.</figcaption></figure><h3><strong>PART 2. Use of Remote Notifications</strong></h3><blockquote>Local and push notifications are great for keeping people informed with timely and relevant content, whether your app is running in the background or inactive. Notifications can display a message, play a distinctive sound, or update a badge on your app icon. <a href="https://developer.apple.com/notifications/">Apple Developer Documentation</a></blockquote><p>Before we jump into how to implement this, let’s refresh our understanding of remote notifications. These notifications appear on a user’s device even if the app isn’t currently open, enabling you to maintain user engagement and provide important information.</p><h4>Step1: Setup SwiftUI Project</h4><p>First, configure the project settings to allow push notifications. You need to add the Push Notifications capability and check background fetch, background processing, and remote notifications of background modes to enable this feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*4fv_nCgqf66ENe7lTwDFiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*c9a5Fm3jqT3wZlaaz0MdGw.png" /></figure><h4>Step2: Configure Apple Push Notification Service</h4><p>Once you’ve set up Firebase and configured your Xcode project, Apple’s APNs (Apple Push Notification service) comes into play. APNs is essential for delivering push notifications to iOS devices, no matter which backend service you’re using. Even though we use Firebase to send notifications, it relies on APNs to actually get those messages delivered to devices.</p><p>First of all, you need to <strong>create a certificate signing request</strong>. To do this;</p><p>Open “Keychain Access”-&gt;Go to Certificate Assistant. -&gt; Choose “Request a Certificate From a Certificate Authority”. -&gt; Enter your email. -&gt; Check “Saved to disk”. -&gt; Click “Continue”. -&gt; Specify where to save and click “Save”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*8tXRyduYQLVkyQlDUkFBTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*R31eCEkqWEXPjmeL7HiqNw.png" /></figure><p>Now, you have a request for a certificate in the place you chose. We’ll use it to make a development certificate.</p><p>The next step is <strong>downloading a development certificate</strong>:</p><p>Go to <a href="http://developer.apple.com/">developer.apple.com</a> → Certificates, Identifiers &amp; Profiles → Identifiers → “your app” → Push Notification → Create Certificate → Choose File (choose the development certificate) → Download</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*iDmJNONni75zbc57kszgkg.png" /></figure><p>You can create a certificate for both development and production if you use a separate debug mode. Creating both sandbox and production certificates will save you trouble in the future.</p><p>Next step is to <strong>export .p12 file</strong>:</p><ul><li>Double click the certificate that you downloaded</li><li>Then, go to “Keychain Access” → select “my certificates” → find the certificate → right click → “export” → “save”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*D0_UadUmDrBnm0CCjw1Rvg.png" /></figure><p>Finally, it is time to upload the certificate to Firebase.</p><p>Open Firebase, and go to Project Settings → Cloud Messaging → APNS Certificates → upload the certificate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHDJYpSaQ-0FRWcN_QiSOg.png" /><figcaption>APNs Certificate is uploaded</figcaption></figure><p>Now, everything seems fine. We just need to add the necessary commands to the AppDelegate file to receive remote notifications from Firebase.</p><h4>Step3: Update AppDelegate File</h4><p>Here are the additional lines that we add to support remote notifications in AppDelegate file:</p><pre>class AppDelegate: NSObject, UIApplicationDelegate {<br>    let gcmMessageIDKey = &quot;gcm.message_id&quot;<br>    func application(_ application: UIApplication,<br>                     didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -&gt; Bool<br>    {<br>        // MARK: Setup cloud messaging<br><br>        FirebaseApp.configure()<br><br>        // MARK: Setup notifications<br><br>        // First request PushNotificationPermission from user<br><br>        Messaging.messaging().delegate = self<br><br>        UNUserNotificationCenter.current().delegate = self<br><br>        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]<br>        UNUserNotificationCenter.current().requestAuthorization(<br>            options: authOptions,<br>            completionHandler: { _, _ in }<br>        )<br><br>        application.registerForRemoteNotifications()<br>        return true<br>    }<br><br>    // MARK: Remote notifications<br><br>    func application(_: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],<br>                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -&gt; Void)<br>    {<br>        if let messageID = userInfo[gcmMessageIDKey] {<br>            print(&quot;Message ID: \(messageID)&quot;)<br>        }<br><br>        print(userInfo)<br>        // This will pass the notification to our app to handle it.<br>        completionHandler(UIBackgroundFetchResult.newData)<br>    }<br><br>    func application(_: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {<br>        print(&quot;Enable to register for remote notifactions&quot;, error)<br>    }<br>}<br><br>extension AppDelegate: MessagingDelegate {<br>    func messaging(<br>        _: Messaging,<br>        didReceiveRegistrationToken fcmToken: String?<br>    ) {<br>        let tokenDict = [&quot;token&quot;: fcmToken ?? &quot;&quot;]<br>        // This token can be used for testing notifications on FCM<br>        NotificationCenter.default.post(<br>            name: Notification.Name(&quot;FCMToken&quot;),<br>            object: nil,<br>            userInfo: tokenDict<br>        )<br>    }<br>}<br><br>extension AppDelegate: UNUserNotificationCenterDelegate {<br>    // Receive displayed notifications for iOS devices.<br>    func userNotificationCenter(_: UNUserNotificationCenter,<br>                                willPresent notification: UNNotification,<br>                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -&gt; Void)<br>    {<br>        let userInfo = notification.request.content.userInfo<br><br>        if let messageID = userInfo[gcmMessageIDKey] {<br>            print(&quot;Message ID: \(messageID)&quot;)<br>        }<br><br>        print(userInfo)<br><br>        // Change this to your preferred presentation option<br>        completionHandler([[.banner, .badge, .sound]])<br>    }<br><br>    func application(application _: UIApplication,<br>                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)<br>    {<br>        #if DEBUG<br>            Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)<br>        #else<br>            Messaging.messaging().setAPNSToken(deviceToken, type: .prod)<br>        #endif<br>    }<br><br>    func userNotificationCenter(_: UNUserNotificationCenter,<br>                                didReceive response: UNNotificationResponse,<br>                                withCompletionHandler completionHandler: @escaping () -&gt; Void)<br>    {<br>        let userInfo = response.notification.request.content.userInfo<br><br>        if let messageID = userInfo[gcmMessageIDKey] {<br>            print(&quot;Message ID from userNotificationCenter didReceive: \(messageID)&quot;)<br>        }<br><br>        print(userInfo)<br><br>        completionHandler()<br>    }<br>}</pre><p>Here’s what matters most in the code when it comes to handling remote notifications:</p><p><strong>Setting Up Firebase and Notifications:</strong></p><ul><li>FirebaseApp.configure(): Gets your app ready for Firebase services.</li><li>Messaging.messaging().delegate = self: Takes care of messages in your app.</li><li>UNUserNotificationCenter.current().delegate = self: Deals with notifications for users.</li><li>UNUserNotificationCenter.current().requestAuthorization(...): Asks users for permission to show notifications in a certain way.</li><li>application.registerForRemoteNotifications(): Puts your app on the list for remote notifications.</li></ul><p><strong>Handling Remote Notifications:</strong></p><ul><li>application(_:didReceiveRemoteNotification:fetchCompletionHandler:): Gets and processes remote notifications. It prints info about the notification and lets the system know your app is done handling it.</li><li>application(_:didFailToRegisterForRemoteNotificationsWithError:): Manages when registering for remote notifications doesn&#39;t work out.</li></ul><p><strong>Using MessagingDelegate and UNUserNotificationCenterDelegate:</strong></p><ul><li>messaging(_:didReceiveRegistrationToken:): Grabs your Firebase Cloud Messaging (FCM) token and shares it for testing.</li><li>userNotificationCenter(_:willPresent:withCompletionHandler:): Deals with notifications received while your app is active. It decides how to show the notification.</li><li>application(_:didRegisterForRemoteNotificationsWithDeviceToken:): Sets up your FCM token using the device&#39;s token from APNs.</li><li>userNotificationCenter(_:didReceive:withCompletionHandler:): Handles when users interact with notifications, showing details about it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*XklEUlupgsEhBrlVjf1fuA.png" /><figcaption>Here we go:) Now let’s send the first test message!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Vxo2SLwBKFaYWlK86EDsA.png" /></figure><p>In this article, I’ve put together a very simple app to help you understand how to use Firebase. I’ve aimed to simplify things by explaining the crucial steps in configuring remote notifications setup.</p><p>I’m excited to connect with you in future articles. Until then, stay curious and keep learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ebe38d265cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/use-of-firebase-for-chat-and-push-notifications-4ebe38d265cc">Unlocking the Power of Firebase: Push Notifications and Beyond</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>