<?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 Amin Faruq on Medium]]></title>
        <description><![CDATA[Stories by Amin Faruq on Medium]]></description>
        <link>https://medium.com/@aminfaruk.fa?source=rss-d416e2d282db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*EhTw3h6K7JrycMPDc8ue_Q.jpeg</url>
            <title>Stories by Amin Faruq on Medium</title>
            <link>https://medium.com/@aminfaruk.fa?source=rss-d416e2d282db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:46:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aminfaruk.fa/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[Handling Inconsistent ISO 8601 Dates in Swift]]></title>
            <link>https://medium.com/devsameday/handling-inconsistent-iso-8601-dates-in-swift-03f03bf4db87?source=rss-d416e2d282db------2</link>
            <guid isPermaLink="false">https://medium.com/p/03f03bf4db87</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Amin Faruq]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 07:13:25 GMT</pubDate>
            <atom:updated>2026-10-01T07:16:29.210Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Apple’s built-in .iso8601 strategy breaks the second a backend returns fractional seconds. Here is a fallback decoder that handles both.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EW8YimtbAxR_JN57y0KGgA.png" /></figure><p>Apple’s official advice for decoding ISO 8601 dates in Swift looks simple:</p><pre>let decoder = JSONDecoder()<br>decoder.dateDecodingStrategy = .iso8601</pre><p>It works on your profile endpoint. You feel good about your code. Then you hit the activity feed, and Swift throws a tantrum:</p><pre>DecodingError.dataCorrupted: Expected date string to be ISO8601-formatted.</pre><p>Check the raw JSON payloads, and you find the culprit:</p><ul><li>Endpoint A: 2026-10-01T12:00:00Z</li><li>Endpoint B: 2026-10-01T12:00:00.342Z</li></ul><p>Same backend, same concept of time, two completely different string formats. One service emits clean UTC, while another runs a Postgres query that dumps fractional seconds into the response.</p><p>You could argue in Slack. You could open a Jira ticket and wait three sprints for the backend team to agree on an API contract. Or you can build a decoding layer that doesn’t blow up every time an ORM changes its default formatting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0BHgPe4WrfUslJOk7XvmQ.png" /></figure><h3>Why Apple .iso8601 Gives Up</h3><p>Under the hood, JSONDecoder.DateDecodingStrategy.iso8601 wraps Apple’s ISO8601DateFormatter with a single default option:</p><pre>[.withInternetDateTime]</pre><p>That option expects standard internet timestamps (yyyy-MM-dd&#39;T&#39;HH:mm:ssZ). The moment a backend returns fractional seconds (.SSS), the parser refuses to parse it and throws DecodingError.dataCorruptedError.</p><p>To make it more annoying, JSONDecoder only accepts one date strategy per instance. There is no built-in way to say &quot;try standard ISO, but fall back to milliseconds if that fails.&quot;</p><h3>The Custom DateFormatter Traps</h3><p>Developers usually try to fix this with a custom decoding closure. That introduces two common mistakes:</p><h4>1. The 12-Hour Device Clock</h4><p>If you reach for a standard DateFormatter, you have to lock its locale:</p><pre>formatter.locale = Locale(identifier: &quot;en_US_POSIX&quot;)</pre><p>Skip this line, and DateFormatter reads the user’s device settings. If someone uses a 12-hour clock (AM/PM) or a non-Gregorian calendar (such as Buddhist or Hijri), the parser fails on standard 24-hour server timestamps. en_US_POSIX stops the user’s calendar settings from breaking your API responses.</p><h4>2. Allocating Formatters in Decoding Loops</h4><p>Allocating DateFormatter or ISO8601DateFormatter is slow. If you allocate a new one inside a decoding closure for a 200-item array, you will drop frames and lock up your UI during scrolls. Formatters belong in static memory, instantiated once.</p><h3>The Fix: Multi-Layer Fallback Formatter</h3><p>Chain the parsers from fastest to most forgiving, and allocate them once:</p><pre>import Foundation<br><br>enum AppDateFormatter{<br>    // 1. Fast ISO8601 formatters<br>    private static let iso8601WithFractionalSeconds: ISO8601DateFormatter = {<br>        let formatter = ISO8601DateFormatter()<br>        formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]<br>        return formatter<br>    }()<br><br>    private static let iso8601Standard: ISO8601DateFormatter = {<br>        let formatter = ISO8601DateFormatter()<br>        formatter.formatOptions = [.withInternetDateTime]<br>        return formatter<br>    }()<br><br>    // 2. POSIX DateFormatters as fallbacks for non-standard timezone offsets<br>    private static let withFractionalSeconds: DateFormatter = {<br>        let formatter = DateFormatter()<br>        formatter.locale = Locale(identifier: &quot;en_US_POSIX&quot;)<br>        formatter.dateFormat = &quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSXXXXX&quot;<br>        return formatter<br>    }()<br><br>    private static let withoutFractionalSeconds: DateFormatter = {<br>        let formatter = DateFormatter()<br>        formatter.locale = Locale(identifier: &quot;en_US_POSIX&quot;)<br>        formatter.dateFormat = &quot;yyyy-MM-dd&#39;T&#39;HH:mm:ssXXXXX&quot;<br>        return formatter<br>    }()<br><br>    /// Parses in order: ISO8601 (fast path) -&gt; POSIX DateFormatter (fallback)<br>    static func date(from string: String) -&gt; Date? {<br>        if let date = iso8601WithFractionalSeconds.date(from: string) {<br>            return date<br>        }<br>        if let date = iso8601Standard.date(from: string) {<br>            return date<br>        }<br>        if let date = withFractionalSeconds.date(from: string) {<br>            return date<br>        }<br>        return withoutFractionalSeconds.date(from: string)<br>    }<br><br>    static func string(from date: Date) -&gt; String {<br>        withoutFractionalSeconds.string(from: date)<br>    }<br>}</pre><h3>Hooking into JSONDecoder</h3><p>Wrap the fallback logic in a reusable factory method on JSONDecoder:</p><pre>extension JSONDecoder{<br>    static func resilientISO8601() -&gt; JSONDecoder {<br>        let decoder = JSONDecoder()<br>        decoder.dateDecodingStrategy = .custom { decoder in<br>            let container = try decoder.singleValueContainer()<br>            let dateString = try container.decode(String.self)<br><br>            guard let date = AppDateFormatter.date(from: dateString) else {<br>                throw DecodingError.dataCorruptedError(<br>                    in: container,<br>                    debugDescription: &quot;Invalid or unsupported ISO 8601 date: \(dateString)&quot;<br>                )<br>            }<br>            return date<br>        }<br>        return decoder<br>    }<br>}</pre><h3>How It Looks in a Real Networking Layer</h3><p>In production, keep decoding logic out of SwiftUI views and behind a clean loader abstraction.</p><h4>1. DTO with Mixed Date Formats</h4><p>A single payload can contain timestamps from different microservices or DB triggers:</p><pre>struct RemoteChallengeDTO: Decodable{<br>    let id: UUID<br>    let goal: String<br>    let status: String<br><br>    let createdAt: Date       // e.g. &quot;2026-09-28T08:30:00.000Z&quot; (fractional seconds)<br>    let startedAt: Date?      // e.g. &quot;2026-10-01T12:00:00.123Z&quot; (fractional seconds)<br>    let deadline: Date?       // e.g. &quot;2026-10-05T18:00:00Z&quot;     (standard ISO 8601)<br>    let updatedAt: Date?<br><br>    func toModel() -&gt; Challenge {<br>        Challenge(<br>            id: id,<br>            goal: goal,<br>            status: status,<br>            createdAt: createdAt,<br>            deadline: deadline<br>        )<br>    }<br>}<br><br>private struct RemoteChallengePageRoot: Decodable{<br>    let data: [RemoteChallengeDTO]<br>}</pre><h4>2. The Remote Loader</h4><p>The loader executes asynchronously using an HTTPClient protocol abstraction:</p><pre>public final class RemoteChallengeLoader{<br>    public enum Error: Swift.Error{<br>        case connectivity<br>        case unauthorized<br>        case invalidData<br>    }<br><br>    private let url: URL<br>    private let client: HTTPClient<br><br>    public init(url: URL, client: HTTPClient) {<br>        self.url = url<br>        self.client = client<br>    }<br><br>    public func load() async throws -&gt; [Challenge] {<br>        let (data, response) = try await client.get(from: url, headers: nil)<br><br>        switch response.statusCode {<br>        case 200:<br>            guard let root = try? JSONDecoder.resilientISO8601()<br>                .decode(RemoteChallengePageRoot.self, from: data) else {<br>                throw Error.invalidData<br>            }<br>            return root.data.map { $0.toModel() }<br><br>        case 401:<br>            throw Error.unauthorized<br><br>        default:<br>            throw Error.invalidData<br>        }<br>    }<br>}</pre><p>If your HTTPClient uses completion closures, bridge it to Swift Concurrency with withCheckedThrowingContinuation.</p><p>Whether the backend sends .000Z, Z, or weird timezone offsets across different properties, every field decodes deterministically.</p><h3>Why This Works</h3><ol><li><strong>Fast-path execution</strong>: ISO8601DateFormatter runs first. It parses RFC 3339 strings directly without standard formatter overhead.</li><li><strong>Deterministic fallback</strong>: The en_US_POSIX DateFormatter catches format variations and offsets that ISO8601DateFormatter rejects.</li><li><strong>No allocation churn</strong>: Formatter instances are static constants. Decoding an array of 500 items incurs zero formatter reallocations.</li><li><strong>Isolated decoding</strong>: Feature code and UI views never care about date quirks. The fix lives entirely in the decoding strategy.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03f03bf4db87" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsameday/handling-inconsistent-iso-8601-dates-in-swift-03f03bf4db87">Handling Inconsistent ISO 8601 Dates in Swift</a> was originally published in <a href="https://medium.com/devsameday">devsameday</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero-Conflict Multi-Environment Setup in iOS Using XcodeGen and .xcconfig]]></title>
            <link>https://medium.com/devsameday/zero-conflict-multi-environment-setup-in-ios-using-xcodegen-and-xcconfig-c0a22c4c7c0a?source=rss-d416e2d282db------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0a22c4c7c0a</guid>
            <category><![CDATA[xcodegen]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Amin Faruq]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 13:31:29 GMT</pubDate>
            <atom:updated>2026-09-28T16:49:23.735Z</atom:updated>
            <content:encoded><![CDATA[<h4>Managing iOS environments, isolating debug tools, and avoiding project.pbxproj merge conflicts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Dl983Lu_PBrFfpNHyoaTA.png" /></figure><p>Every iOS developer working on a team eventually hits the same set of problems:</p><ol><li><strong>The </strong><strong>project.pbxproj merge conflict:</strong> Two developers add files or touch build settings on separate branches. Merging them produces dozens of conflicting hexadecimal UUIDs in a file nobody wants to edit by hand.</li><li><strong>The wrong endpoint shipping:</strong> A developer forgets to flip an environment boolean or uncomment an API URL before a release, sending staging traffic to production.</li><li><strong>App overwrite collisions:</strong> Installing a staging build replaces the production app on your test device because both share the same bundle identifier.</li><li><strong>Debug code leaking to the App Store:</strong> In-app network loggers, debug consoles, or test accounts remain active in production releases.</li></ol><p>Managing environments directly inside Xcode build configurations quickly turns into repetitive, error-prone manual labor.</p><p>Here is the setup I use to manage environments cleanly: declarative project generation with XcodeGen, layered .xcconfig files for build settings, and type-safe Swift configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*b3NnB-WI1KGLY2vlw8mN7Q.png" /></figure><h3>Architecture Overview</h3><p>This setup relies on three components:</p><ol><li><strong>Declarative project specifications:</strong> I add .xcodeproj to .gitignore. The project file is generated on demand from a plain-text YAML spec using <a href="https://github.com/yonaskolb/XcodeGen">XcodeGen</a>.</li><li><strong>Layered </strong><strong>.xcconfig inheritance:</strong> Shared build settings live in Base.xcconfig. Environment files (Dev.xcconfig, Prod.xcconfig) inherit from base and override only their specific values.</li><li><strong>Type-safe Swift consumption:</strong> Swift code reads environment values through Info.plist variables populated at build time, avoiding scattered #if DEBUG macros.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muv_W6M01PJUpP1B_Y5yJQ.png" /></figure><h3>Step 1: The Layered .xcconfig Hierarchy</h3><p>Configuration files (.xcconfig) move build settings out of opaque project files into editable plain text.</p><h4>1. Base.xcconfig</h4><p>This file contains universal settings shared across every target and build type:</p><pre>// Base.xcconfig<br>PRODUCT_NAME = MyApp<br>SWIFT_VERSION = 5.0<br>DEVELOPMENT_TEAM = YOUR_TEAM_ID<br>GENERATE_INFOPLIST_FILE = YES<br>INFOPLIST_FILE = MyApp/Info.plist<br><br>TARGETED_DEVICE_FAMILY = 1,2<br>INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait<br>INFOPLIST_KEY_UIRequiresFullScreen = YES<br>INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO</pre><h4>2. Dev.xcconfig</h4><p>Dev builds inherit base settings and override identifiers and endpoints:</p><pre>// Dev.xcconfig<br>#include &quot;Base.xcconfig&quot;<br><br>PRODUCT_NAME = MyAppDev<br>PRODUCT_BUNDLE_IDENTIFIER = com.company.app.dev<br>APP_DISPLAY_NAME = MyApp Dev<br>INFOPLIST_KEY_CFBundleDisplayName = $(APP_DISPLAY_NAME)<br>ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon-Dev<br><br>// Slashes escaped using empty variable syntax<br>BASE_URL = https:/$()/api-dev.example.com<br><br>// Custom compilation flags<br>SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) DEV ENABLE_DEBUG_TOOLS<br><br>MARKETING_VERSION = 1.0.0<br>CURRENT_PROJECT_VERSION = 42</pre><h4>3. Prod.xcconfig</h4><p>Production settings target the real API and release bundle identifier:</p><pre>// Prod.xcconfig<br>#include &quot;Base.xcconfig&quot;<br><br>PRODUCT_NAME = MyApp<br>PRODUCT_BUNDLE_IDENTIFIER = com.company.app<br>APP_DISPLAY_NAME = MyApp<br>INFOPLIST_KEY_CFBundleDisplayName = $(APP_DISPLAY_NAME)<br>ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon<br><br>BASE_URL = https:/$()/api.example.com<br><br>SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) PROD<br><br>MARKETING_VERSION = 1.0.0<br>CURRENT_PROJECT_VERSION = 1</pre><h4>Handling the .xcconfig URL Comment Trap</h4><p>In .xcconfig files, double slashes (//) mark the start of a comment. Writing:</p><pre>BASE_URL = &lt;https://api.example.com&gt;</pre><p>causes Xcode to discard everything after https:, breaking the URL during compilation.</p><p>To prevent this, use the empty variable workaround:</p><pre>BASE_URL = https:/$()/api.example.com</pre><p>Xcode evaluates $() as an empty string, keeping the protocol prefix intact without triggering comment parsing.</p><h3>Step 2: Bridging Values Through Info.plist</h3><p>Instead of writing custom run-script build phases to inject variables into Swift, expose them through Info.plist:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;&lt;http://www.apple.com/DTDs/PropertyList-1.0.dtd&gt;&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br>    &lt;key&gt;BaseURL&lt;/key&gt;<br>    &lt;string&gt;$(BASE_URL)&lt;/string&gt;<br>    &lt;key&gt;CFBundleDisplayName&lt;/key&gt;<br>    &lt;string&gt;$(APP_DISPLAY_NAME)&lt;/string&gt;<br>    &lt;key&gt;CFBundleShortVersionString&lt;/key&gt;<br>    &lt;string&gt;$(MARKETING_VERSION)&lt;/string&gt;<br>    &lt;key&gt;CFBundleVersion&lt;/key&gt;<br>    &lt;string&gt;$(CURRENT_PROJECT_VERSION)&lt;/string&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><p>Xcode replaces $(BASE_URL) and $(APP_DISPLAY_NAME) with the values defined in whichever .xcconfig is currently active.</p><h3>Step 3: Eliminating Duplication in XcodeGen with targetTemplates</h3><p>When creating multiple application targets (such as MyApp and MyAppDev), manually copying source lists and framework dependencies across targets creates maintenance overhead.</p><p>XcodeGen solves this with targetTemplates:</p><pre>name: MyApp<br>options:<br>  bundleIdPrefix: com.company<br>  deploymentTarget:<br>    iOS: &quot;16.6&quot;<br>  xcodeVersion: &quot;16.0&quot;<br><br>packages:<br>  Netfox:<br>    url: https://github.com/kasketis/netfox<br>    from: 1.21.0<br><br>targetTemplates:<br>  AppTemplate:<br>    type: application<br>    platform: iOS<br>    sources:<br>      - path: MyApp<br>        excludes:<br>          - Info.plist<br>    dependencies:<br>      - package: Netfox<br><br>targets:<br>  MyApp:<br>    templates:<br>      - AppTemplate<br>    configFiles:<br>      Debug: Configurations/Prod.xcconfig<br>      Release: Configurations/Prod.xcconfig<br><br>  MyAppDev:<br>    templates:<br>      - AppTemplate<br>    configFiles:<br>      Debug: Configurations/Dev.xcconfig<br>      Release: Configurations/Dev.xcconfig<br><br>schemes:<br>  MyApp Dev:<br>    build:<br>      targets:<br>        MyAppDev: all<br><br>  MyApp Prod:<br>    build:<br>      targets:<br>        MyApp: all</pre><p>Both targets share identical source files and package definitions through AppTemplate. Switching environments in Xcode only requires picking MyApp Dev or MyApp Prod from the scheme selector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*r-K7RaHrUZZ9nQqWLFk8dw.png" /></figure><h3>Step 4: Isolating In-App Debug Tools</h3><p>Internal diagnostics, such as network loggers or developer menus, must never compile into App Store binaries.</p><p>Because Dev.xcconfig defines:</p><pre>SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) DEV ENABLE_DEBUG_TOOLS</pre><p>I conditionally import and initialize diagnostics directly in Swift:</p><pre>import SwiftUI<br><br>#if ENABLE_DEBUG_TOOLS<br>import netfox<br>#endif<br><br>@main<br>struct MyApp: App{<br>    init() {<br>        setupDiagnostics()<br>    }<br><br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br><br>    private func setupDiagnostics() {<br>        #if ENABLE_DEBUG_TOOLS<br>        NFX.sharedInstance().start()<br>        print(&quot;Debug tools initialized.&quot;)<br>        #endif<br>    }<br>}</pre><p>When building MyApp Prod, the compiler strips this block entirely. The diagnostic code does not exist inside the production binary.</p><h3>Step 5: Type-Safe Configuration in Swift</h3><p>Accessing Bundle.main.infoDictionary directly throughout your UI or networking layer leads to scattered string lookups. I encapsulate configuration inside a single enum:</p><pre>import Foundation<br><br>enum AppConfig{<br>    static var baseURL: URL {<br>        guard let urlString = Bundle.main.object(forInfoDictionaryKey: &quot;BaseURL&quot;) as? String,<br>              let url = URL(string: urlString) else {<br>            fatalError(&quot;BaseURL is missing or invalid in Info.plist&quot;)<br>        }<br>        return url<br>    }<br><br>    static var appDisplayName: String {<br>        (Bundle.main.object(forInfoDictionaryKey: &quot;CFBundleDisplayName&quot;) as? String) ?? &quot;MyApp&quot;<br>    }<br>}</pre><p>View models and network loaders reference AppConfig.baseURL directly without needing to know which environment is running.</p><h3>Step 6: Automating Generation with a Makefile</h3><p>To keep project generation identical across developer machines and CI runners, I wrap the invocation in a script:</p><p>scripts/generate.sh:</p><pre>#!/bin/bash<br>set -eo pipefail<br><br>if ! command -v xcodegen &amp;&gt; /dev/null; then<br>    echo &quot;Error: xcodegen is not installed. Run &#39;brew install xcodegen&#39; first.&quot;<br>    exit 1<br>fi<br><br>echo &quot;Generating Xcode Project...&quot;<br>xcodegen generate --spec project.yml<br>echo &quot;Project generated successfully.&quot;</pre><p>And in the root Makefile:</p><pre>.PHONY: generate<br><br>generate:<br> @./scripts/generate.sh</pre><p>With *.xcodeproj added to .gitignore, setting up a fresh clone takes one command:</p><pre>$ make generate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*TZLSN9nXoGVFsUkekONLDw.png" /></figure><h3>Comparison: Traditional Setup vs. XcodeGen + .xcconfig</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FKJIKX%2F2%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FKJIKX%2F2%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FKJIKX%2Fplain-s.png%3Fv%3D2&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="391" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ca67f80415110b04a45a7786cd33499/href">https://medium.com/media/5ca67f80415110b04a45a7786cd33499/href</a></iframe><p>How does your team handle environment configurations? Do you use XcodeGen, Tuist, or built-in Xcode schemes? Let me know in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0a22c4c7c0a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsameday/zero-conflict-multi-environment-setup-in-ios-using-xcodegen-and-xcconfig-c0a22c4c7c0a">Zero-Conflict Multi-Environment Setup in iOS Using XcodeGen and .xcconfig</a> was originally published in <a href="https://medium.com/devsameday">devsameday</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoupling Swift Networking: Moving Beyond the God Manager]]></title>
            <link>https://medium.com/devsameday/decoupling-swift-networking-moving-beyond-the-god-manager-930d01d3ad06?source=rss-d416e2d282db------2</link>
            <guid isPermaLink="false">https://medium.com/p/930d01d3ad06</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Amin Faruq]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 06:29:35 GMT</pubDate>
            <atom:updated>2026-09-16T06:44:47.426Z</atom:updated>
            <content:encoded><![CDATA[<h4>Applying Interface Segregation to build swappable, use-case driven HTTP layers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-evfnn3mu8Oc7zD6DlAbg.png" /></figure><p>Every iOS developer writes this at least once:</p><pre>final class APIManager{<br>    static let shared = APIManager()<br>    private init() {}<br><br>    func login(...)<br>    func fetchFeed(...)<br>    func updateProfile(...)<br>    func uploadAvatar(...)<br>    func fetchSettings(...)<br>    // ... 40 other unrelated endpoints dumped here<br>}</pre><p>Wrapping this in actor APIManager doesn&#39;t fix the design. Actors protect mutable state from data races; they do nothing for architectural coupling. When an app grows beyond two screens, APIManager.swift becomes a 2,000-line bottleneck:</p><ol><li><strong>Daily merge conflicts:</strong> Every engineer on the team edits the same file for every PR.</li><li><strong>Interface Segregation Principle (ISP) broken:</strong> My feed screen only needs a list of posts, but it depends on an object that knows how to reset passwords and change subscription tiers.</li><li><strong>Miserable testing:</strong> Testing anything downstream forces you into URLProtocol interception or fragile subclasses.</li><li><strong>Third-party lock-in:</strong> Alamofire imports, Codable DTOs, and HTTP status codes bleed directly into SwiftUI views.</li></ol><h3>The Fix: Lightweight Use-Case Protocols and Transport Abstraction</h3><blockquote>“Clients should not be forced to depend upon interfaces that they do not use.”</blockquote><blockquote><em>— Robert C. Martin (Uncle Bob)</em></blockquote><p>Instead of routing all network calls through one object, split networking into small, use-case protocols and isolate the transport layer behind an interface.</p><p>This is not classic VIPER. You do not need an Interactor, a Presenter, a Router, and five coordination protocols just to display a list. Enterprise ceremony burns teams out.</p><p>This approach keeps dependencies one-directional and modular:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dnj9E2Oi9ZEhB7FsrRklsQ.png" /><figcaption>dependency diagram</figcaption></figure><h3>Step 1: Define the Contract in the Domain Layer</h3><pre>import Foundation<br><br>// Pure Domain Model: No Codable, no network metadata<br>public struct FeedItem: Identifiable, Hashable{<br>    public let id: UUID<br>    public let title: String<br>    public let timestamp: Date<br><br>    public init(id: UUID, title: String, timestamp: Date) {<br>        self.id = id<br>        self.title = title<br>        self.timestamp = timestamp<br>    }<br>}</pre><pre>// Single use-case protocol<br>public protocol FeedLoader{<br>    func load() async throws -&gt; [FeedItem]<br>}</pre><p>The Domain layer specifies only what the application needs: an input, an output, and potential errors.</p><h3>Step 2: Abstract the HTTP Transport</h3><p>An HTTP client should transport bytes, not decode business models. Status code interpretation and JSON parsing belong to use-case adapters, not the transport layer:</p><pre>import Foundation<br><br>public protocol HTTPClientTask{<br>    func cancel()<br>}<br><br>public struct HTTPBody: Equatable{<br>    public enum ContentType: Equatable{<br>        case json<br>        case multipart(boundary: String)<br>    }<br><br>    public let data: Data<br>    public let contentType: ContentType<br><br>    public init(data: Data, contentType: ContentType) {<br>        self.data = data<br>        self.contentType = contentType<br>    }<br>}<br><br>public protocol HTTPClient{<br>    typealias Result = Swift.Result&lt;(Data, HTTPURLResponse), Error&gt;<br><br>    @discardableResult<br>    func get(<br>        from url: URL,<br>        headers: [String: String]?,<br>        completion: @escaping (Result) -&gt; Void<br>    ) -&gt; HTTPClientTask<br><br>    @discardableResult<br>    func post(<br>        _ url: URL,<br>        headers: [String: String]?,<br>        body: HTTPBody?,<br>        completion: @escaping (Result) -&gt; Void<br>    ) -&gt; HTTPClientTask<br>}</pre><h3>Step 3: Implement Swappable Transport Engines</h3><p>Because HTTPClient is a protocol, swapping URLSession for Alamofire requires modifying zero domain code.</p><h4>Option A: Native URLSessionHTTPClient</h4><pre>import Foundation<br><br>public final class URLSessionHTTPClient: HTTPClient{<br>    struct UnexpectedValuesRepresentation: Error{}<br><br>    private let session: URLSession<br><br>    public init(session: URLSession = URLSession(configuration: .ephemeral)) {<br>        self.session = session<br>    }<br><br>    @discardableResult<br>    public func get(<br>        from url: URL,<br>        headers: [String: String]? = nil,<br>        completion: @escaping (HTTPClient.Result) -&gt; Void<br>    ) -&gt; HTTPClientTask {<br>        var request = URLRequest(url: url)<br>        request.httpMethod = &quot;GET&quot;<br>        request.allHTTPHeaderFields = headers<br>        return perform(request, completion: completion)<br>    }<br><br>    @discardableResult<br>    public func post(<br>        _ url: URL,<br>        headers: [String: String]? = nil,<br>        body: HTTPBody? = nil,<br>        completion: @escaping (HTTPClient.Result) -&gt; Void<br>    ) -&gt; HTTPClientTask {<br>        var request = URLRequest(url: url)<br>        request.httpMethod = &quot;POST&quot;<br>        request.allHTTPHeaderFields = headers<br>        if let body {<br>            request.httpBody = body.data<br>            switch body.contentType {<br>            case .json:<br>                request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>            case let .multipart(boundary):<br>                request.setValue(&quot;multipart/form-data; boundary=\(boundary)&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>            }<br>        }<br>        return perform(request, completion: completion)<br>    }<br><br>    private func perform(_ request: URLRequest, completion: @escaping (HTTPClient.Result) -&gt; Void) -&gt; HTTPClientTask {<br>        let task = session.dataTask(with: request) { data, response, error in<br>            completion(URLSessionHTTPClient.map(data: data, response: response, error: error))<br>        }<br>        task.resume()<br>        return URLSessionHTTPClientTask(task: task)<br>    }<br><br>    private static func map(data: Data?, response: URLResponse?, error: Error?) -&gt; HTTPClient.Result {<br>        if let error {<br>            return .failure(error)<br>        } else if let data, let response = response as? HTTPURLResponse {<br>            return .success((data, response))<br>        } else {<br>            return .failure(UnexpectedValuesRepresentation())<br>        }<br>    }<br>}<br><br>private final class URLSessionHTTPClientTask: HTTPClientTask{<br>    private let task: URLSessionTask<br><br>    init(task: URLSessionTask) {<br>        self.task = task<br>    }<br><br>    func cancel() {<br>        task.cancel()<br>    }<br>}</pre><h4>Option B: AlamofireHTTPClient</h4><p>If your project requires request retriers, certificate pinning, or network interceptors, implement HTTPClient with Alamofire:</p><pre>import Alamofire<br>import Foundation<br><br>public final class AlamofireHTTPClient: HTTPClient{<br>    struct UnexpectedValuesRepresentation: Error{}<br><br>    private let session: Alamofire.Session<br>    private let validatesStatusCodes: Bool<br><br>    public init(session: Alamofire.Session = Alamofire.Session.default, validatesStatusCodes: Bool = false) {<br>        self.session = session<br>        self.validatesStatusCodes = validatesStatusCodes<br>    }<br><br>    @discardableResult<br>    public func get(<br>        from url: URL,<br>        headers: [String: String]? = nil,<br>        completion: @escaping (HTTPClient.Result) -&gt; Void<br>    ) -&gt; HTTPClientTask {<br>        let request = session.request(url, method: .get, headers: HTTPHeaders(headers ?? [:]))<br>        return perform(request, completion: completion)<br>    }<br><br>    @discardableResult<br>    public func post(<br>        _ url: URL,<br>        headers: [String: String]? = nil,<br>        body: HTTPBody? = nil,<br>        completion: @escaping (HTTPClient.Result) -&gt; Void<br>    ) -&gt; HTTPClientTask {<br>        var urlRequest = URLRequest(url: url)<br>        urlRequest.httpMethod = HTTPMethod.post.rawValue<br>        urlRequest.allHTTPHeaderFields = headers<br>        if let body {<br>            urlRequest.httpBody = body.data<br>            switch body.contentType {<br>            case .json:<br>                urlRequest.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>            case let .multipart(boundary):<br>                urlRequest.setValue(&quot;multipart/form-data; boundary=\(boundary)&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>            }<br>        }<br>        let request = session.request(urlRequest)<br>        return perform(request, completion: completion)<br>    }<br><br>    private func perform(_ request: DataRequest, completion: @escaping (HTTPClient.Result) -&gt; Void) -&gt; HTTPClientTask {<br>        if validatesStatusCodes {<br>            request.validate()<br>        }<br>        let responseHandler = request.response { response in<br>            completion(AlamofireHTTPClient.map(data: response.data, response: response.response, error: response.error))<br>        }<br>        return AlamofireHTTPClientTask(request: responseHandler)<br>    }<br><br>    private static func map(data: Data?, response: HTTPURLResponse?, error: Error?) -&gt; HTTPClient.Result {<br>        if let error {<br>            return .failure(error)<br>        } else if let response {<br>            return .success((data ?? Data(), response))<br>        } else {<br>            return .failure(UnexpectedValuesRepresentation())<br>        }<br>    }<br>}<br><br>private final class AlamofireHTTPClientTask: HTTPClientTask{<br>    private let request: Request<br><br>    init(request: Request) {<br>        self.request = request<br>    }<br><br>    func cancel() {<br>        request.cancel()<br>    }<br>}</pre><h3>Step 4: Implement the Adapter in Infrastructure</h3><p>This class conforms to FeedLoader and consumes HTTPClient. It bridges the transport completion handler into modern Swift concurrency while decoding raw JSON into domain models:</p><pre>public final class RemoteFeedLoader: FeedLoader{<br>    private let url: URL<br>    private let client: HTTPClient<br><br>    public enum Error: Swift.Error{<br>        case connectivity<br>        case unauthorized<br>        case invalidData<br>    }<br><br>    public init(url: URL, client: HTTPClient) {<br>        self.url = url<br>        self.client = client<br>    }<br><br>    public func load() async throws -&gt; [FeedItem] {<br>        try await withCheckedThrowingContinuation { continuation in<br>            client.get(from: url, headers: nil) { result in<br>                switch result {<br>                case let .success((data, response)):<br>                    if response.statusCode == 200,<br>                       let root = try? JSONDecoder().decode(RemoteFeedRoot.self, from: data) {<br>                        continuation.resume(returning: root.data.map { $0.toDomain() })<br>                    } else if response.statusCode == 401 {<br>                        continuation.resume(throwing: Error.unauthorized)<br>                    } else {<br>                        continuation.resume(throwing: Error.invalidData)<br>                    }<br>                case .failure:<br>                    continuation.resume(throwing: Error.connectivity)<br>                }<br>            }<br>        }<br>    }<br>}<br><br>// Private DTOs stay in this file<br>private struct RemoteFeedRoot: Decodable{<br>    let data: [RemoteFeedItemDTO]<br>}<br><br>private struct RemoteFeedItemDTO: Decodable{<br>    let id: UUID<br>    let headline: String<br>    let createdAt: Date<br><br>    func toDomain() -&gt; FeedItem {<br>        FeedItem(id: id, title: headline, timestamp: createdAt)<br>    }<br>}</pre><p>The DTO is private. If a backend engineer renames headline to title_text, I update this file only. The UI and Domain layers remain unchanged.</p><h3>Step 5: Plug Into Any Presentation Pattern</h3><p>Your presentation layer is an implementation detail. The use-case interface works whether you prefer plain SwiftUI with view state or MVVM.</p><h4>Option A: Plain SwiftUI with .task</h4><pre>struct FeedView: View{<br>    let loader: FeedLoader<br>    @State private var items: [FeedItem] = []<br>    @State private var isLoading = false<br>    @State private var errorMessage: String?<br><br>    var body: some View {<br>        NavigationStack {<br>            List(items) { item in<br>                Text(item.title)<br>            }<br>            .overlay {<br>                if isLoading { ProgressView() }<br>            }<br>            .task {<br>                isLoading = true<br>                defer { isLoading = false }<br>                do {<br>                    items = try await loader.load()<br>                } catch {<br>                    errorMessage = error.localizedDescription<br>                }<br>            }<br>        }<br>    }<br>}</pre><h4>Option B: MVVM</h4><pre>@MainActor<br>public final class FeedViewModel: ObservableObject{<br>    @Published public private(set) var items: [FeedItem] = []<br>    @Published public private(set) var isLoading = false<br><br>    private let loader: FeedLoader<br><br>    public init(loader: FeedLoader) {<br>        self.loader = loader<br>    }<br><br>    public func loadFeed() async {<br>        isLoading = true<br>        defer { isLoading = false }<br>        items = (try? await loader.load()) ?? []<br>    }<br>}</pre><h3>Step 6: Frictionless Tests and Previews</h3><p>Testing requires no live connection, no custom URL protocols, and no mocking libraries:</p><pre>final class FeedViewModelTests: XCTestCase{<br>    func test_loadFeed_setsItemsOnSuccess() async {<br>        let expectedItems = [FeedItem(id: UUID(), title: &quot;Test&quot;, timestamp: Date())]<br>        let stub = FeedLoaderStub(result: .success(expectedItems))<br>        let sut = FeedViewModel(loader: stub)<br><br>        await sut.loadFeed()<br><br>        XCTAssertEqual(sut.items, expectedItems)<br>    }<br>}<br><br>private struct FeedLoaderStub: FeedLoader{<br>    let result: Result&lt;[FeedItem], Error&gt;<br><br>    func load() async throws -&gt; [FeedItem] {<br>        try result.get()<br>    }<br>}</pre><p>SwiftUI canvas previews render immediately:</p><pre>#Preview {<br>    FeedView(loader: FeedLoaderStub(result: .success([<br>        FeedItem(id: UUID(), title: &quot;Mock Item 1&quot;, timestamp: Date()),<br>        FeedItem(id: UUID(), title: &quot;Mock Item 2&quot;, timestamp: Date())<br>    ])))<br>}</pre><h3>Step 7: Compose at the Application Root</h3><p>At the composition root, you choose which transport engine powers the app:</p><pre>@main<br>struct MyApp: App{<br>    var body: some Scene {<br>        WindowGroup {<br>            let client = URLSessionHTTPClient()<br>            let loader = RemoteFeedLoader(<br>                url: URL(string: &quot;https://api.example.com/v1/feed&quot;)!,<br>                client: client<br>            )<br><br>            FeedView(loader: loader)<br>        }<br>    }<br>}</pre><h3>Comparison: Singleton vs. Use-Case Protocols</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FLCLjZ%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FLCLjZ%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FLCLjZ%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="481" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6506a31705ba2d813a371411f1527f2/href">https://medium.com/media/f6506a31705ba2d813a371411f1527f2/href</a></iframe><p>How does your team organize networking in Swift? Are you still maintaining a central singleton, or did you transition to use-case protocols? Let me know in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=930d01d3ad06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsameday/decoupling-swift-networking-moving-beyond-the-god-manager-930d01d3ad06">Decoupling Swift Networking: Moving Beyond the God Manager</a> was originally published in <a href="https://medium.com/devsameday">devsameday</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Can Write Your Unit Tests. That’s Exactly the Problem.]]></title>
            <link>https://medium.com/@aminfaruk.fa/ai-can-write-your-unit-tests-thats-exactly-the-problem-780d6d109ec7?source=rss-d416e2d282db------2</link>
            <guid isPermaLink="false">https://medium.com/p/780d6d109ec7</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Amin Faruq]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 19:16:07 GMT</pubDate>
            <atom:updated>2026-09-03T19:16:07.109Z</atom:updated>
            <content:encoded><![CDATA[<p><em>AI can generate 50 tests in seconds. The harder part is knowing which 50 tests should actually exist in the first place.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VP_--FL2RGwAzhhVvB6YWQ.png" /></figure><p>AI coding agents are having a massive moment right now.</p><p>You open up your IDE, highlight a Swift class, type <em>“write unit tests for this”</em>, and five seconds later-boom. A glorious wall of green checkmarks. Dopamine hit unlocked. You feel like a 10x engineer.</p><p>Then you push to CI. And everything immediately catches fire.</p><p>One test randomly times out. Another has a hardcoded Task.sleep(nanoseconds: 2_000_000_000) buried inside it like an absolute crime against humanity. A couple of tests try to subclass URLProtocol with messy global state, others pull in a bloated third-party mocking framework, and a few just give up and ping real network endpoints with arbitrary delays all just to stub out a single response.</p><p>That’s when the marketing fantasy collides with cold, hard reality:</p><blockquote><strong><em>AI is phenomenal at churning out code that passes. It is fundamentally clueless about what a good test architecture actually looks like.</em></strong></blockquote><p>And let’s be fair: that’s not even the AI’s fault. You didn’t give it an architectural strategy. You just begged it to <em>“write tests.”</em> So it did. Exactly what you asked for, warts and all.</p><h3>The Gimmick vs. The Reality</h3><p>Here is the seductive trap that almost every developer falls into once they get their hands on modern coding agents:</p><ol><li>Build the feature.</li><li>Hack on it until the UI looks right.</li><li>Tell the AI agent: <em>“Generate unit tests for this file.”</em></li><li>Watch the test runner light up green.</li><li>Ship it and call it a day.</li></ol><p>It feels hyper productive. On paper, your code coverage graph looks stellar. But let’s not delude ourselves: you’re not doing Test-Driven Development. You’re doing <strong>Test-After Development</strong>.</p><p>And in production iOS apps, that distinction will make or break your sanity.</p><p>When the implementation already exists, the AI treats your code as the gospel truth. Modern reasoning models are brilliant at pattern matching, but <strong>AI lacks product authority</strong>. It doesn’t test what the system <em>should</em> do; it merely validates <strong>what your flawed code currently does</strong>.</p><p>The edge case you forgot while rushing to meet a sprint deadline? It’s not in your production code. And because the AI cannot read your mind or guess undocumented business requirements, it assumes that omission was completely intentional. The agent will happily generate 30 green tests validating your broken logic without batting an eye.</p><p>AI can iterate on existing behavior all day long. But it cannot magically hallucinate business requirements that you never designed.</p><p>That’s why before I touch Swift, before I open XCTest, and definitely before I unleash an AI agent, I start with <strong>behavior</strong>.</p><h3>Step 1: Stress Test the Behavior Before Touching Xcode</h3><p>Let’s be pragmatic: I don’t write formal BDD specifications for every 5 line string formatter or basic SwiftUI view. That’s dogmatic nonsense.</p><p>But for <strong>boundary components</strong> network loaders, authentication coordinators, local persistence stores, and offline sync engines where unhandled edge cases cause 2 AM production fire drills mapping out the contract upfront is non negotiable.</p><p>Before writing a single line of RemoteHallOfShameStatsLoader, I map out its contract. Not implementation trivia, but pure behavior and failure modes.</p><p>Think of it like benchmarking a new device: you don’t just test the peak clock speed; you test the thermal throttling when things get ugly.</p><pre>Load Hall of Shame Stats<br><br>Data:<br>- A URL to the stats endpoint<br>- An HTTP client<br><br>Primary course (happy path):<br>1. Execute load command with a given URL.<br>2. Request data from the URL.<br>3. Receive a 200 HTTP response with valid JSON.<br>4. Deliver parsed stats to the caller.<br><br>Alternative / Fallback courses:<br>- Partial JSON → missing status keys default to zero counts<br><br>Error courses (sad paths):<br>- Network failure → connectivity error<br>- Non-200 response → invalid data<br>- Invalid JSON → invalid data<br><br>Lifecycle / Memory safety:<br>- SUT deallocated before response → deliver nothing (no-op)<br><br>Side effects:<br>- Initialization must not trigger any network request.<br>- Calling load twice must produce two distinct requests.</pre><p>That took five minutes of deliberate thinking. But now we have something infinitely more valuable than 50 hallucinated tests: <strong>an unambiguous specification.</strong></p><h3>The Tests Should Fall Out Naturally</h3><p>Once the behavior contract is locked in, naming your test cases becomes almost mechanical and in software architecture, boring is a superpower:</p><pre>test_init_doesNotRequestDataFromURL<br>test_loadStats_requestsDataFromURL<br>test_loadStats_twiceRequestsDataFromURLTwice<br>test_loadStats_deliversConnectivityErrorOnClientError<br>test_loadStats_deliversInvalidDataOnNon200Status<br>test_loadStats_deliversInvalidDataOn200WithInvalidJSON<br>test_loadStats_deliversStatsOn200WithValidJSON<br>test_loadStats_deliversZeroCountsForMissingStatusKeys<br>test_loadStats_doesNotDeliverResultAfterSUTInstanceHasBeenDeallocated</pre><p>Nine concrete scenarios. Nine deterministic tests. Every single one maps to a real business requirement or a known edge case. Nothing invented after the fact; no blind spots left behind.</p><h3>The Three Ground Rules I Never Let AI Break</h3><p>Even with the contract in hand, I still don’t let the agent run wild. I enforce three strict architectural constraints.</p><h4>Rule #1: Control Time. Never Sleep.</h4><p>Using sleep() in a unit test is an immediate red flag. No Thread.sleep(...), no DispatchQueue.asyncAfter(...), and no hopeful Task.sleep(...) delays where the test sits there praying the async scheduler finishes in time.</p><p>Whether you’re handling closure completions or awaiting actors in Swift Concurrency: <strong>the test must synchronously dictate when the response arrives, not the system clock.</strong></p><h4>Rule #2: Centralize Creation in makeSUT()</h4><p>Never let individual tests construct their own ad-hoc object graphs. Centralize initialization in a single factory function that also handles automated memory leak tracking:</p><pre>private func makeSUT(<br>    url: URL = URL(string: &quot;http://any-url.com&quot;)!,<br>    file: StaticString = #filePath,<br>    line: UInt = #line<br>) -&gt; (sut: RemoteHallOfShameStatsLoader, client: HTTPClientSpy) {<br>    let client = HTTPClientSpy()<br>    let sut = RemoteHallOfShameStatsLoader(url: url, client: client)<br><br>    trackForMemoryLeaks(client, file: file, line: line)<br>    trackForMemoryLeaks(sut, file: file, line: line)<br><br>    return (sut, client)<br>}</pre><p>Boring? Absolutely. But it guarantees that when your dependency graph evolves tomorrow, you update one factory function instead of fixing 40 broken unit tests. Spending ten minutes setting up a clean factory and a protocol spy is infinitely cheaper than spending the next six months debugging CI pipeline flakiness.</p><h4>Rule #3: Spy the Interaction, Don’t Just Flip a Boolean</h4><p>I constantly see AI generated tests that look like this:</p><pre>var isLoadCalled = false<br>// ...<br>isLoadCalled = true</pre><p>That’s technically a test, but it tells you almost nothing about the real interaction. Did it request the right URL? Did it fire once or five times?</p><p>Instead, build a lightweight Spy that records chronological events:</p><pre>final class HTTPClientSpy: HTTPClient {<br>    private var messages = [(url: URL, completion: (HTTPClient.Result) -&gt; Void)]()<br><br>    var requestedURLs: [URL] {<br>        messages.map(\.url)<br>    }<br><br>    func get(from url: URL, completion: @escaping (HTTPClient.Result) -&gt; Void) {<br>        messages.append((url, completion))<br>    }<br><br>    func complete(with error: Error, at index: Int = 0) {<br>        messages[index].completion(.failure(error))<br>    }<br><br>    func complete(withStatusCode code: Int, data: Data, at index: Int = 0) {<br>        let response = HTTPURLResponse(<br>            url: requestedURLs[index],<br>            statusCode: code,<br>            httpVersion: nil,<br>            headerFields: nil<br>        )!<br>        messages[index].completion(.success((data, response)))<br>    }<br>}</pre><p>The magic here isn’t just that it’s a Spy. The magic is that <strong>the test is the puppet master.</strong></p><p><em>(A quick architectural note for modern Swift purists: We use completion handlers in this example because synchronously capturing a closure in an in-memory array is the purest, most transparent demonstration of the “waiting room” pattern. If your boundaries are built entirely on </em><em>async/await, the exact same mental model applies: your spy holds an in-memory </em><em>CheckedContinuation or an isolated test actor. The goal remains identical the test synchronously triggers resolution; it never sits around waiting for system thread pools).</em></p><p><em>(And why not just stub </em><em>URLSession with </em><em>URLProtocol? Because </em><em>URLProtocol relies on global class registration, risks cross test state pollution in parallel runners, and still incurs Apple&#39;s internal URLSession dispatch overhead. A protocol based Spy is pure in-memory Swift: 100% isolated, zero framework magic, and executes in microseconds. Under Swift 6 with strict concurrency checking, isolating your test suite and spies to </em><em>@MainActor guarantees zero data races without extra synchronization primitives).</em></p><h3>The Spy Is a Waiting Room</h3><p>When the SUT calls client.get(from: url), the Spy doesn&#39;t touch the internet or dispatch to a background thread. It simply grabs the completion closure and holds it in memory.</p><p>Now your test gets to decide the timeline synchronously:</p><ul><li><em>“Fail with a network error right now.”</em></li><li><em>“Hand back a 200 with valid stats payload.”</em></li><li><em>“Return a 200 with broken JSON.”</em></li></ul><p>Zero network calls. Zero threading hops. Zero milliseconds wasted.</p><pre>func test_loadStats_deliversConnectivityErrorOnClientError() {<br>    let (sut, client) = makeSUT()<br><br>    expect(sut, toCompleteWith: failure(.connectivity)) {<br>        client.complete(with: NSError(domain: &quot;Test&quot;, code: 0))<br>    }<br>}</pre><p><em>(Where </em><em>expect is our synchronous test helper that executes the action block and verifies that </em><em>sut delivers the exact expected enum result).</em></p><h3>The Test Most Developers Forget: The Ghost Object</h3><p>Here’s my absolute favorite edge case one that AI almost never writes on its own, but quietly causes weird crashes and state bugs in production: <strong>What happens when the user leaves the screen before the server responds?</strong></p><pre>func test_loadStats_doesNotDeliverResultAfterSUTInstanceHasBeenDeallocated() {<br>    let client = HTTPClientSpy()<br>    // SUT must be optional so we can explicitly simulate mid-flight deallocation:<br>    var sut: RemoteHallOfShameStatsLoader? = RemoteHallOfShameStatsLoader(url: URL(string: &quot;http://any-url.com&quot;)!, client: client)<br>    var receivedResults = [RemoteHallOfShameStatsLoader.Result]()<br><br>    sut?.loadStats { receivedResults.append($0) }<br>    sut = nil // User navigated back. Screen popped.<br><br>    // Server finishes later.<br>    // Contract requirement: SUT&#39;s production code MUST capture `[weak self]`<br>    // and bail out (`guard let self else { return }`) before invoking the completion block.<br>    client.complete(withStatusCode: 200, data: anyData())<br><br>    XCTAssertTrue(receivedResults.isEmpty)<br>}    sut?.loadStats { receivedResults.append($0) }<br>    sut = nil // User navigated back. Screen popped.</pre><p>Think about what happens here: The network request starts. The user swipes back. The view controller deallocates. Two seconds later, the backend sends a payload.</p><p>If your closure captured self strongly, that dead object is still hanging around in memory, processing data for a view that was destroyed seconds ago. This test locks down that memory lifecycle explicitly.</p><h3>Stop Writing Essay Prompts: Codify Architecture into AI Skills</h3><p>Typing frantic, 500 word essay prompts into chat every single time you need a unit test isn’t engineering it’s prayer. You will forget a constraint, the AI will inevitably slip back into its lazy habits, and you will spend the rest of the morning arguing with a chatbot.</p><p>Prompting on the fly doesn’t scale across a team.</p><p>Instead, <strong>encode your architectural rules directly into your repository’s AI Skills or Rules</strong> (such as .agents/skills/tdd/SKILL.md or .cursorrules). Treat your testing standards like architecture as code:</p><pre>---<br>name: tdd<br>description: Enforce Clean Architecture unit test patterns — makeSUT, spies, synchronous completion, retain-cycle detection, and failure modes.<br>metadata:<br>  layer: test<br>---<br><br># iOS TDD &amp; Architecture Standards<br><br>## 1. Test Construction &amp; Memory Safety<br>- NEVER instantiate System Under Test (SUT) directly in test methods.<br>- ALWAYS use a private `makeSUT(...) -&gt; (sut: SUTType, doubles...)` factory.<br>- ALWAYS register all instances with `trackForMemoryLeaks(instance, file: file, line: line)` inside `makeSUT`.<br><br>## 2. Test Doubles &amp; Isolation<br>- NEVER mock concrete Apple frameworks (`URLSession`, `CoreData`, `NotificationCenter`).<br>- Use pure Swift `Spy` implementations that capture invocations as an enum log (`ReceivedMessage`) and store completion closures.<br>- The Spy must never invoke completions automatically; the test drives responses explicitly.<br><br>## 3. Execution &amp; Determinism<br>- Tests must be 100% synchronous and deterministic.<br>- STRICTLY FORBIDDEN: `Thread.sleep`, `Task.sleep`, `DispatchQueue.asyncAfter`, or arbitrary expectation timeouts.<br>- Use the shared `expect(sut, toCompleteWith:when:)` assertion helper.<br><br>## 4. Mandatory Test Checklist per Boundary Layer<br>Every remote use-case test suite must cover:<br>1. `test_init_doesNotRequestDataFromURL` (no side effects on init)<br>2. `test_load_requestsDataFromURL`<br>3. `test_load_twiceRequestsDataFromURLTwice`<br>4. Client/Network error delivery<br>5. Non-200 HTTP status code matrix (`[199, 201, 300, 401, 500]`)<br>6. Malformed / 200 invalid JSON handling<br>7. Alternative / Fallback JSON schemas (graceful degradation)<br>8. `test_load_doesNotDeliverResultAfterSUTInstanceHasBeenDeallocated`</pre><p>Once this skill is indexed in your workspace, your day to day prompt to Claude, Cursor, or your agent of choice becomes delightfully concise:</p><blockquote>“Implement the unit tests for <em>RemoteHallOfShameStatsLoader</em> covering scenarios 4 through 7 from our behavior contract.&quot;</blockquote><p>Because the agent already loads the architectural constitution from the skill, it automatically produces clean, compliant code. The AI handles the syntax and the repetitive permutations, but <strong>you supplied the behavioral contract</strong>.</p><h3>XCTest vs. Swift Testing: The Framework Doesn’t Matter</h3><p>A common objection from iOS engineers is: <em>“Does this pattern still apply if our team is migrating to Apple’s modern </em><em>Swift Testing framework?&quot;</em></p><p>The answer is an emphatic <strong>yes</strong>.</p><p>Look at how the exact same status code permutation test looks in classic XCTest versus modern Swift Testing:</p><h4>Option A: Classic XCTest</h4><pre>final class RemoteHallOfShameStatsLoaderTests: XCTestCase {<br><br>    func test_loadStats_deliversInvalidDataOnNon200Status() {<br>        let samples = [199, 201, 300, 401, 500]<br><br>        samples.forEach { code in<br>            let (sut, client) = makeSUT()<br><br>            expect(sut, toCompleteWith: failure(.invalidData)) {<br>                client.complete(withStatusCode: code, data: anyData())<br>            }<br>        }<br>    }<br>}</pre><h4>Option B: Modern Swift Testing</h4><pre>import Testing<br><br>@Suite(&quot;RemoteHallOfShameStatsLoader Tests&quot;)<br>struct RemoteHallOfShameStatsLoaderTests {<br><br>    @Test(<br>        &quot;Delivers invalid data on non-200 HTTP status codes&quot;,<br>        arguments: [199, 201, 300, 401, 500]<br>    )<br>    func loadStats_deliversInvalidDataOnNon200Status(statusCode: Int) {<br>        let (sut, client) = makeSUT()<br><br>        expect(sut, toCompleteWith: failure(.invalidData)) {<br>            client.complete(withStatusCode: statusCode, data: anyData())<br>        }<br>    }<br>}</pre><p>Notice what happened here:</p><ul><li>In Swift Testing, we swap XCTestCase for @Suite, replace test_ prefixes with @Test, and get native parameterized tests via arguments: [...].</li><li><strong>But the architectural core </strong><strong>makeSUT(), the isolated </strong><strong>HTTPClientSpy, and the synchronous completion waiting room did not change by a single millimeter.</strong></li></ul><p><em>(An architectural nuance for sharp eyed engineers: in </em><em>XCTest, </em><em>trackForMemoryLeaks relies on </em><em>XCTestCase.addTeardownBlock. Because Swift Testing suites are commonly value type </em><em>structs without an XCTest lifecycle, you have two clean ways to verify memory deallocation: make your </em><em>@Suite a </em><em>final class with a </em><em>deinit assertion, or use a scope based </em><em>defer check with a weak reference. The runner&#39;s lifecycle mechanism shifts, but your commitment to catching retain cycles never wavers).</em></p><p>XCTest won’t save you from a bloated, coupled architecture. And Swift Testing won’t magically prevent flakiness if you let an AI agent sprinkle Task.sleep all over your suite.</p><p>The test runner is just the paint on the wall. The architectural decoupling is the foundation holding the building up. Use whichever framework your team prefers.</p><h3>AI Should Be Your Typist, Not Your Lead Architect</h3><p>When developers complain that AI writes bad tests, it’s usually because they handed the agent total architectural freedom.</p><p>The AI agent is inherently optimizing for <strong>“make this test pass right now with whatever code compiles.”</strong></p><p>You are optimizing for <strong>“keep this test suite fast, deterministic, readable, and maintainable two years from now when the team has doubled.”</strong></p><p>Those two goals are completely at odds unless you establish the boundaries first.</p><h3>The Real World Trade Off</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*BzT76rReI5HbwcLkZQzm9Q.png" /></figure><h3>The Takeaway</h3><p>Before touching Xcode, define the behavior. Map out the happy path, the ugly paths, and the weird edge cases especially for critical boundary components. Turn those into clear test names, then follow the red-green-refactor loop.</p><p>Encode your architectural patterns and Spies into repo level AI Skills so the agent never has to guess your standards. Then, and only then, let the AI generate the repetitive permutations.</p><p>Whether you run on XCTest or Swift Testing, the law remains identical: TDD was never about typing test code. It has always been about <strong>deciding what the software is supposed to do before you start convincing yourself that your implementation works.</strong></p><p>AI can generate 50 unit tests before your morning coffee finishes brewing. But it can’t decide which failure modes actually matter to your users, and it definitely won’t stop you from shipping a beautifully green checked disaster to the App Store.</p><p><strong>That part is still your job.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=780d6d109ec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Thread-Safe 401 Auto-Refresh in Swift: A Clean Architecture Approach]]></title>
            <link>https://medium.com/devsameday/building-a-thread-safe-401-auto-refresh-in-swift-a-clean-architecture-approach-b11eba91b52e?source=rss-d416e2d282db------2</link>
            <guid isPermaLink="false">https://medium.com/p/b11eba91b52e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Amin Faruq]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 13:39:41 GMT</pubDate>
            <atom:updated>2026-09-09T14:52:06.531Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Three requests go out. One token expires. Without a lock, you get three refresh calls, a burned refresh token, and a login screen that flickers like a bad strobe light.</blockquote><p>Handling HTTP requests in Swift has never been easier. With a few lines of URLSession or Alamofire, you fetch data, decode JSON, populate your views, and call it a day.</p><p>But what happens when the user’s Access Token expires <em>while three requests are already in flight</em>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*s1HOnGM-seBjVqtg4htoOw.jpeg" /></figure><p>The naive approach is to catch the 401 and call a refreshToken() function. That works fine in a demo where you fire one request and wait. It falls apart the moment your app is a real app.</p><p>If your app launches and fires three requests at once feed, profile, notifications and the token is already expired, all three fail at the same instant. Without concurrency management, your app doesn’t call refreshToken() once. It calls it <strong>three times, simultaneously</strong>, from three different completion handlers that have no idea the other two exist.</p><p>The result: invalidated tokens, requests that silently die, and a refresh flow that occasionally logs the user out for no reason they can explain to support.</p><p>Here’s the flow I actually wanted, and the one this article builds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRG0Ejf4g-h9XsBHdofAjA.png" /></figure><p>One refresh call. Every pending request waits, then retries with the new token. Let’s build it and keep Alamofire and the network layer far away from anything that looks like business logic.</p><h4>1. The Blueprint: Hiding Alamofire Behind Domain Protocols</h4><p>The rule is simple: domain and business logic don’t get to know a third-party framework exists. To keep Alamofire out of the domain layer, I start with a pure HTTPClient protocol:</p><pre>public protocol HTTPClient {<br>    typealias Result = Swift.Result&lt;(Data, HTTPURLResponse), Error&gt;<br><br>    @discardableResult<br>    func get(from url: URL, headers: [String: String]?, completion: @escaping (Result) -&gt; Void) -&gt; HTTPClientTask<br><br>    @discardableResult<br>    func post(_ url: URL, headers: [String: String]?, body: HTTPBody?, completion: @escaping (Result) -&gt; Void) -&gt; HTTPClientTask<br>}</pre><p>Then I build AlamofireHTTPClient as the adapter that actually implements it.</p><p>Here’s a detail that will burn an afternoon if you don’t know it going in: Alamofire’s RequestInterceptor.retry only fires if the request <em>throws</em> an error. By default, Alamofire treats a 401 as a &quot;success,&quot; because technically the HTTP round trip completed fine — the server just said no.</p><p>So AlamofireHTTPClient has to explicitly force validation:</p><pre>public final class AlamofireHTTPClient: HTTPClient {<br>    private let session: Alamofire.Session<br>    private let validatesStatusCodes: Bool<br><br>    // ... init &amp; methods ...<br><br>    private func perform(_ request: DataRequest, completion: @escaping (HTTPClient.Result) -&gt; Void) -&gt; HTTPClientTask {<br>        if validatesStatusCodes {<br>            request.validate() // Forces 4xx/5xx to throw an AFError<br>        }<br>        let responseHandler = request.response { response in<br>            completion(AlamofireHTTPClient.map(data: response.data, response: response.response, error: response.error))<br>        }<br>        return AlamofireHTTPClientTask(request: responseHandler)<br>    }<br>}</pre><p>With validatesStatusCodes = true on the authenticated client, a 401 becomes an AFError.responseValidationFailed and gets properly handed off to the interceptor. Without this, the interceptor&#39;s retry method never runs, and you&#39;ll spend a very confusing hour wondering why your beautifully written lock never even gets touched.</p><h4>2. Thread-Safe Token Refreshing</h4><p>The actual logic lives in TokenRefreshInterceptor. It conforms to Alamofire&#39;s RequestInterceptor and does two jobs:</p><ol><li>adapt: attaches the Authorization: Bearer &lt;token&gt; header to outgoing requests.</li><li>retry: catches 401s, pauses the failed requests, refreshes the token once, and retries everything that was waiting.</li></ol><p>To stop three simultaneous 401s from firing three simultaneous refresh calls, I use an NSLock to gate access and a queue to hold pending retries:</p><pre>public final class TokenRefreshInterceptor: RequestInterceptor, @unchecked Sendable {<br>    private let lock = NSLock()<br>    private var isRefreshing = false<br>    private var pendingRetries: [(RetryResult) -&gt; Void] = []<br><br>    public func retry(<br>        _ request: Request,<br>        for session: Alamofire.Session,<br>        dueTo error: Error,<br>        completion: @escaping (RetryResult) -&gt; Void<br>    ) {<br>        guard<br>            let response = request.task?.response as? HTTPURLResponse,<br>            response.statusCode == 401,<br>            request.retryCount == 0 // Only retry once<br>        else {<br>            completion(.doNotRetry)<br>            return<br>        }<br><br>        lock.lock()<br>        pendingRetries.append(completion) // Queue the retry callback<br><br>        guard !isRefreshing else {<br>            lock.unlock()<br>            return // Let the active refresh handle it<br>        }<br>        isRefreshing = true<br>        lock.unlock()<br><br>        performRefresh() // Execute the actual network call to get a new token<br>    }<br>}</pre><p>The first 401 to arrive flips isRefreshing to true and kicks off performRefresh(). Every 401 that arrives after it just gets appended to pendingRetries and does nothing else it doesn&#39;t fire a second refresh, it just waits its turn.</p><p>When performRefresh() succeeds, I save the new tokens to TokenStore and walk through pendingRetries, telling Alamofire to .retry every paused request with the fresh token. One network call for the refresh, no matter how many requests failed at once.</p><h4>3. The Infinite Loop Trap</h4><p>Here’s a mistake that’s easy to make and annoying to debug: using the <em>same authenticated client</em> to fire the refresh request itself.</p><p>Think about what happens if the refresh token is also expired. The refresh call returns a 401. The interceptor, doing exactly what you told it to do, catches that 401 and tries to refresh again. Which fails again. Which triggers another refresh. Your app is now stuck in a loop, silently hammering your auth server, and the user is staring at a spinner that will never resolve.</p><p>The fix is to make sure the refresh request never goes through the interceptor at all. I build the dependencies in a Composition Root, AuthenticatedSessionFactory:</p><pre>public enum AuthenticatedSessionFactory {<br>    public static func make(...) -&gt; (client: AlamofireHTTPClient, interceptor: TokenRefreshInterceptor) {<br><br>        // 1. A PLAIN client that has no interceptor and does NOT validate status codes.<br>        let plainClient = AlamofireHTTPClient(session: Alamofire.Session(configuration: sessionConfiguration))<br><br>        // 2. The Interceptor uses the plain client to perform the refresh.<br>        let interceptor = TokenRefreshInterceptor(..., httpClient: plainClient, ...)<br><br>        // 3. The AUTHENTICATED client uses the interceptor and validates status codes.<br>        let authenticatedSession = Alamofire.Session(configuration: sessionConfiguration, interceptor: interceptor)<br>        let authenticatedClient = AlamofireHTTPClient(session: authenticatedSession, validatesStatusCodes: true)<br><br>        return (authenticatedClient, interceptor)<br>    }<br>}</pre><p>Two separate Alamofire.Session instances, two separate clients. The plain one has no interceptor, so its 401 goes nowhere and just fails cleanly which is exactly what should happen when the refresh token itself is dead.</p><h4>4. TDD: Test-Driving the Interceptor</h4><p>Testing async concurrency, locks, and network retries usually means booting a simulator, hitting a mock server, or both. With the domain isolated from Alamofire, none of that is necessary the whole flow can run in memory.</p><p>To intercept Alamofire’s outgoing requests without touching the real network, I use a custom URLProtocolStub:</p><pre>final class URLProtocolStub: URLProtocol {<br>    private static var result: ((URLRequest) throws -&gt; StubResult)?<br><br>    // ... overrides for canInit, canonicalRequest, etc. ...<br><br>    override func startLoading() {<br>        guard let result = URLProtocolStub.result else { return }<br><br>        do {<br>            let stub = try result(request)<br>            switch stub {<br>            case let .failure(error):<br>                client?.urlProtocol(self, didFailWithError: error)<br>            case let .success(data, response):<br>                if let response {<br>                    client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)<br>                }<br>                if let data {<br>                    client?.urlProtocol(self, didLoad: data)<br>                }<br>                client?.urlProtocolDidFinishLoading(self)<br>            }<br>        } catch {<br>            client?.urlProtocol(self, didFailWithError: error)<br>        }<br>    }<br>}</pre><p>Injected into an ephemeral URLSessionConfiguration, this makes Alamofire return mocked responses instantly, no server involved. I wrap the setup in a standard makeSUT factory:</p><pre>private func makeSUT(<br>    tokenStore: TokenStore,<br>    refreshClient: HTTPClient = HTTPClientSpy(),<br>    deviceID: String = anyDeviceID,<br>    file: StaticString = #filePath,<br>    line: UInt = #line<br>) -&gt; (client: AlamofireHTTPClient, interceptor: TokenRefreshInterceptor) {<br><br>    let interceptor = TokenRefreshInterceptor(<br>        tokenStore: tokenStore,<br>        refreshURL: refreshURL(),<br>        httpClient: refreshClient,<br>        deviceID: deviceID<br>    )<br><br>    let configuration = URLSessionConfiguration.ephemeral<br>    configuration.protocolClasses = [URLProtocolStub.self]<br>    let session = Alamofire.Session(configuration: configuration, interceptor: interceptor)<br><br>    let client = AlamofireHTTPClient(session: session, validatesStatusCodes: true)<br>    trackForMemoryLeaks(client, file: file, line: line)<br><br>    return (client, interceptor)<br>}</pre><p>With lightweight doubles like TokenStoreSpy and HTTPClientSpy, I can assert on the exact behavior that matters that concurrent 401s only ever trigger one refresh call:</p><pre>func test_retry_refreshesOnlyOnceDuringConcurrentUnauthorizedRequests() {<br>    let store = TokenStoreSpy(accessToken: &quot;access-token&quot;, refreshToken: &quot;refresh-token&quot;)<br>    let refreshClient = HTTPClientSpy() // Captures outgoing refresh requests<br>    let (client, _) = makeSUT(tokenStore: store, refreshClient: refreshClient)<br><br>    // Stub the first 2 requests to fail with 401, then succeed with 200<br>    var requestCount = 0<br>    URLProtocolStub.stub { _ in<br>        requestCount += 1<br>        if requestCount &lt;= 2 {<br>            return .success(data: Data(), response: makeHTTPURLResponse(statusCode: 401))<br>        }<br>        return .success(data: Data(), response: makeHTTPURLResponse(statusCode: 200))<br>    }<br><br>    // Fire two requests simultaneously<br>    let exp = expectation(description: &quot;Wait for both results&quot;)<br>    exp.expectedFulfillmentCount = 2<br>    _ = client.get(from: anyURL()) { _ in exp.fulfill() }<br>    _ = client.get(from: anyURL()) { _ in exp.fulfill() }<br><br>    // Complete the refresh request successfully<br>    refreshClient.complete(withStatusCode: 200, data: makeRefreshJSON())<br>    wait(for: [exp], timeout: 2.0)<br><br>    // Assert that the refresh endpoint was only hit exactly once!<br>    XCTAssertEqual(refreshClient.receivedMessages.count, 1)<br>}</pre><p>This is the test that actually matters in this whole article. Not “does the token refresh” of course it does, that’s the easy path. The one that matters is “does it refresh <em>exactly once</em> when three things fail at the same millisecond.” That’s the bug that doesn’t show up in a demo and does show up at 2am when your crash reporter lights up.</p><p>I also guard against memory leaks the same way as the rest of the codebase an XCTestCase extension using addTeardownBlock:</p><pre>extension XCTestCase {<br>    func trackForMemoryLeaks(_ instance: AnyObject, file: StaticString = #filePath, line: UInt = #line) {<br>        addTeardownBlock { [weak instance] in<br>            XCTAssertNil(instance, &quot;Instance should have been deallocated. Potential memory leak.&quot;, file: file, line: line)<br>        }<br>    }<br>}</pre><p>Drop trackForMemoryLeaks into makeSUT, and any strong closure capture in the interceptor fails the test immediately instead of quietly leaking in production.</p><h4>5. Decoupling Navigation from Networking</h4><p>If the refresh token itself gets rejected the user logged out on another device, or it simply expired the app needs to boot the user back to the Login screen.</p><p>It’s tempting to just broadcast a logout event straight from the network layer with NotificationCenter or some presentation helper. Don&#39;t. Networking code has no business knowing your UI state or navigation hierarchy exists.</p><p>Instead, TokenRefreshInterceptor exposes a plain callback:</p><pre>public var onAuthFailure: (() -&gt; Void)?</pre><p>Navigation itself is owned by the Composition Root, AppRouter, which holds the single source of truth for the app&#39;s flow:</p><pre>@MainActor<br>final class AppRouter: ObservableObject {<br>    enum Flow: Equatable {<br>        case restoring<br>        case login<br>        case authenticated(Session)<br>    }<br><br>    // The source of truth for the active screen<br>    @Published private(set) var flow: Flow = .restoring<br><br>    // Build the thread-safe HTTP client using our Factory<br>    private lazy var authenticatedSetup: (client: AlamofireHTTPClient, interceptor: TokenRefreshInterceptor) = {<br>        AuthenticatedSessionFactory.make(<br>            tokenStore: tokenStore,<br>            baseURL: baseURL,<br>            deviceID: deviceIDProvider.deviceID()<br>        )<br>    }()<br><br>    private var authenticatedClient: AlamofireHTTPClient { authenticatedSetup.client }<br><br>    init() {<br>        // Route auth failure (refresh token rejected) back to the login flow.<br>        authenticatedSetup.interceptor.onAuthFailure = { [weak self] in<br>            Task { @MainActor in<br>                self?.forceSignOut()<br>            }<br>        }<br>    }<br><br>    private func forceSignOut() {<br>        tokenStore.clearTokens()<br>        flow = .login // Triggers UI update instantly<br>    }<br>}</pre><p>When the app enters .authenticated, AppRouter injects authenticatedClient into the feature loaders that need it:</p><pre>    private func enterAuthenticated(session: Session) {<br>        // 1. Inject the robust authenticatedClient into feature loaders<br>        let feedLoader = RemoteFeedLoader(<br>            url: baseURL.appendingPathComponent(&quot;api/v1/feed&quot;),<br>            client: authenticatedClient<br>        )<br>        let profileLoader = RemoteProfileLoader(<br>            url: baseURL.appendingPathComponent(&quot;api/v1/profile&quot;),<br>            client: authenticatedClient<br>        )<br><br>        let viewModel = HomeViewModel(session: session, feedLoader: feedLoader)<br><br>        // 2. Navigation is handled at the Composition Root, not inside the ViewModel<br>        viewModel.onSignOut = { [weak self] in<br>            self?.forceSignOut()<br>        }<br><br>        // 3. Shift app state<br>        homeViewModel = viewModel<br>        flow = .authenticated(session)<br>    }</pre><p>And here’s what the presentation layer actually sees which is to say, almost nothing about auth:</p><pre>@MainActor<br>final class HomeViewModel: ObservableObject {<br>    @Published var items: [FeedItem] = []<br>    @Published var errorMessage: String?<br><br>    private let feedLoader: FeedLoader // Pure domain protocol<br><br>    init(feedLoader: FeedLoader) {<br>        self.feedLoader = feedLoader<br>    }<br><br>    func loadData() {<br>        feedLoader.load { [weak self] result in<br>            switch result {<br>            case let .success(items):<br>                self?.items = items<br><br>            case let .failure(error):<br>                // Handle standard domain errors (offline, server error, etc.)<br>                // Notice what&#39;s missing: no 401 handling, no token refresh logic!<br>                self?.errorMessage = error.localizedDescription<br>            }<br>        }<br>    }<br>}</pre><p><em>(This </em><em>HomeViewModel is a simplified example a production version would also handle loading states, pagination, and various UI actions. The point worth noticing is what&#39;s absent: zero 401 checks, zero refresh logic. That entire concern lives one layer down, where it belongs.)</em></p><p>At the root, SwiftUI just renders whatever flow currently is:</p><pre>@main<br>struct MyApp: App {<br>    @StateObject private var router = AppRouter()<br><br>    var body: some Scene {<br>        WindowGroup {<br>            RootView(router: router)<br>        }<br>    }<br>}<br><br>struct RootView: View {<br>    @ObservedObject var router: AppRouter<br><br>    var body: some View {<br>        ZStack {<br>            switch router.flow {<br>            case .restoring:<br>                SplashView()<br><br>            case .login:<br>                LoginView(viewModel: router.loginViewModel)<br><br>            case .authenticated:<br>                if let viewModel = router.homeViewModel {<br>                    HomeRootView(<br>                        viewModel: viewModel,<br>                        makeCreateItemViewModel: router.makeCreateItemViewModel<br>                    )<br>                }<br>            }<br>        }<br>        .animation(.easeInOut(duration: 0.3), value: router.flow)<br>        .onAppear {<br>            router.start()<br>        }<br>    }<br>}</pre><p>When the refresh token finally dies for good, AppRouter sets flow = .login, and SwiftUI transitions to the login screen with the network layer never having known a navigation stack existed.</p><h4>The Verdict</h4><pre>┌────────────────────────────────────────────────────────────────────────┐<br>│ THE TRADE-OFF, HONESTLY                                                │<br>│                                                                        │<br>│ Setup time:              Slower (Factory, protocols, interceptor)      │<br>│ Race condition risk:     Zero (Single lock, single refresh call)       │<br>│ Test execution:          Instant (No simulator, no live server)        │<br>│ Infinite refresh loops:  Zero (Refresh call bypasses the interceptor)  │<br>│ Presentation layer:      Doesn&#39;t know 401s exist                       │<br>└────────────────────────────────────────────────────────────────────────┘</pre><p>Factor Naive refreshToken() on 401 Locked Interceptor + Clean Architecture Setup time Fast (a few lines in a completion handler) Slower (protocol, adapter, factory, interceptor) Concurrent 401 handling Fires one refresh per failed request Exactly one refresh, everyone else waits Infinite loop risk High if the refresh call reuses the same client None — refresh request bypasses the interceptor entirely Testability Requires live server or heavy mocking Fully in-memory with URLProtocolStub Presentation layer coupling ViewModels often end up checking status codes ViewModels see only domain errors</p><h4>My rule of thumb:</h4><ul><li><strong>Skip it</strong> if your token stays alive until doomsday.</li><li><strong>Build it</strong> the moment your app fires more than one request on launch and uses a refresh-token flow.</li></ul><p>The lock and the factory don’t make the token refresh flow faster to write. What they buy you is the thing that actually matters: three requests failing at the exact same millisecond turns into one refresh call, one set of new tokens, and zero infinite loops instead of a race condition you’ll be debugging from a stack trace with no clear repro steps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b11eba91b52e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsameday/building-a-thread-safe-401-auto-refresh-in-swift-a-clean-architecture-approach-b11eba91b52e">Building a Thread-Safe 401 Auto-Refresh in Swift: A Clean Architecture Approach</a> was originally published in <a href="https://medium.com/devsameday">devsameday</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture in the Apple Ecosystem: Over-Engineering Masterclass or Actually Useful?]]></title>
            <link>https://medium.com/devsameday/clean-architecture-in-the-apple-ecosystem-over-engineering-masterclass-or-actually-useful-4a164e735652?source=rss-d416e2d282db------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a164e735652</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[macos-development]]></category>
            <dc:creator><![CDATA[Amin Faruq]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 11:02:31 GMT</pubDate>
            <atom:updated>2026-09-09T15:04:23.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GeUjSvcfbWtWe7n8l2oJiA.png" /></figure><blockquote><em>I separated SwiftUI, SwiftData, and business logic across 3 modular targets just to build a habit counter for Mac, iPhone, and Apple Watch. Was it worth the boilerplate pain?</em></blockquote><p>Apple wants you to believe that iOS development is pure sunshine and rainbows.</p><p>Watch any WWDC session and the narrative is always the same: throw a @State here, slap a @Query macro directly inside your View, sprinkle some magic preview traits, and <em>boom</em>—you’ve built an app in 15 minutes.</p><p>That works like a charm… if your app is a single-screen hackathon prototype. But the moment you want to build an offline-first app that runs seamlessly across <strong>macOS (including a live Menu Bar item), iOS, and watchOS</strong>, Apple’s “simple” declarative dream quickly degenerates into a tangled spaghetti nightmare.</p><p>In my latest project, <a href="https://github.com/aminfaruq/streakOS-project"><strong>StreakOS</strong></a> (a minimalist habit tracker where every goal is an incremental counter), I decided to go full Clean Architecture: <strong>Zero SwiftUI in the domain, strict boundary separation, and a three-target modular workspace.</strong></p><p>Was it an engineering triumph? Or did I just spend weeks over-engineering a glorified tally counter?</p><p>Let’s roast my own architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*e5ZdR2qiMq_1Xbl1Ach9bA.jpeg" /></figure><h4><strong>The Blueprint: The 3-Target Modular Split</strong></h4><p>Before we dissect the wins and the scars, here is how the workspace is structured:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNOM0nm4ygBiQiG1WwnHCA.png" /></figure><ol><li><strong>StreakOSFramework (Domain &amp; Infrastructure):</strong> Pure business logic (DailyRecord, Item, DateNavigationWindow) and SwiftData persistence adapters. Imports zero UIKit and zero SwiftUI.</li><li><strong>StreakOSPresentation (Presentation Layer):</strong> ProgressFeedViewModel and ItemFormViewModel. It only depends on the domain protocols and Combine.</li><li><strong>App Targets (</strong><strong>StreakOSMacApp, </strong><strong>StreakOSApp, </strong><strong>StreakOSWatchApp):</strong> Thin &quot;Composition Roots&quot; that assemble the dependencies, install views, and render UI.</li></ol><p>Let’s look at what this purity bought me.</p><h4><strong>Where Clean Architecture Saved My Sanity</strong></h4><p><strong>1. Zero-Simulator Unit Testing (Sub-Second Speed)<br></strong>Testing UI code in Xcode is an exercise in existential dread. Waiting 40 seconds for the iPhone 16 Simulator to boot just to test if a counter increments from 4 to 5 makes you question your career choices.</p><p>In StreakOS, habit progress is managed by DailyRecord—a pure, immutable value type:</p><pre>// Pure, beautiful, unpolluted Swift domain logic<br>public struct DailyRecord: Hashable {<br>    public let currentCount: Int<br>    public let isCompleted: Bool<br><br>    public func incrementing(by amount: Int = 1, targetCount: Int) -&gt; DailyRecord {<br>        guard !isCompleted else { return self }<br>        let newCount = currentCount + amount<br>        return DailyRecord(<br>            id: id, itemId: itemId, date: date,<br>            currentCount: newCount,<br>            isCompleted: newCount &gt;= targetCount,<br>            timerStartDate: timerStartDate,<br>            createdAt: createdAt, updatedAt: Date()<br>        )<br>    }<br>}</pre><p>Because there are no database or UI frameworks attached, testing edge cases is blazing fast. I wrote <strong>181 unit tests</strong> across 20 test files.</p><p>When I hit Cmd+U, the entire test suite executes in <strong>under 450 milliseconds</strong>. No simulator. No mocked database containers. Just pure math.</p><pre>Test Suite &#39;All tests&#39; passed at 0.412 seconds.<br>Executed 181 tests, with 0 failures in 20 test suites.</pre><p><strong>2. Built-in Automatic Memory Leak Detection<br></strong>By standardizing on a makeSUT() factory pattern, every single test automatically tracks retain cycles using addTeardownBlock:</p><pre>private func makeSUT(<br>    file: StaticString = #filePath,<br>    line: UInt = #line<br>) -&gt; (sut: LocalDailyProgressLoader, itemStore: ItemStoreSpy, recordStore: DailyRecordStoreSpy) {<br>    let itemStore = ItemStoreSpy()<br>    let recordStore = DailyRecordStoreSpy()<br>    let sut = LocalDailyProgressLoader(itemStore: itemStore, dailyRecordStore: recordStore)<br><br>    trackForMemoryLeaks(sut, file: file, line: line)<br>    trackForMemoryLeaks(itemStore, file: file, line: line)<br>    trackForMemoryLeaks(recordStore, file: file, line: line)<br><br>    return (sut, itemStore, recordStore)<br>}</pre><p>If a closure in a ViewModel accidentally captures self strongly, Xcode fails the unit test right then and there. I don&#39;t even need to open Instruments.</p><p><strong>3. Multi-Platform Without Copy-Paste Tears<br></strong>Ever tried maintaining separate apps for macOS, iOS, and Apple Watch? Usually, developers resort to copy-pasting code or creating a chaotic web of #if os(iOS) preprocessor macros.</p><p>With this architecture:</p><ul><li>StreakOSApp uses a UIKit SceneDelegate wrapping a UIHostingController.</li><li>StreakOSMacApp uses SwiftUI with a hidden title bar and a standalone MenuBarExtra popup.</li><li>StreakOSWatchApp renders minimalist watch rows.</li></ul><p><strong>All three platforms share the exact same </strong><strong>ProgressFeedViewModel.</strong> When CloudKit pushes a remote update (NSPersistentStoreRemoteChange), the notification is debounced, the ViewModel refreshes, and the UI updates simultaneously across your Mac menu bar, your iPhone screen, and your wrist.</p><h4>The Brutal Price of Clean Architecture 💀</h4><p>Now, let’s stop patting myself on the back and talk about the ugly truth. Clean Architecture in Swift comes with a heavy <strong>Boilerplate Tax.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*g0FYMbmyTCNE5Jb2BBQZgg.jpeg" /></figure><p><strong>1. The SwiftData “Mapping Hell”<br></strong>SwiftData models (SDItem, SDDailyRecord) must be classes annotated with @Model. But domain models (Item, DailyRecord) must be pure structs.</p><p>Because the domain layer is forbidden from knowing what SwiftData is, every piece of data must pass through a bidirectional translation meat grinder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6EybVCogLIWtdgJY__nMQ.png" /></figure><p>Here is a glimpse of the mapper tax:</p><pre>enum SDItemMapper {<br>    static func toDomain(_ sdItem: SDItem) -&gt; Item {<br>        Item(<br>            id: sdItem.id,<br>            name: sdItem.name,<br>            icon: sdItem.icon,<br>            type: ItemType(rawValue: sdItem.itemTypeRawValue) ?? .count,<br>            targetCount: sdItem.targetCount,<br>            startDate: sdItem.startDate,<br>            endDate: sdItem.endDate,<br>            displayOrder: sdItem.displayOrder,<br>            createdAt: sdItem.createdAt,<br>            updatedAt: sdItem.updatedAt<br>        )<br>    }<br><br>    static func toSDModel(_ item: Item) -&gt; SDItem {<br>        SDItem(<br>            id: item.id,<br>            name: item.name,<br>            icon: item.icon,<br>            itemTypeRawValue: item.type.rawValue,<br>            targetCount: item.targetCount,<br>            startDate: item.startDate,<br>            endDate: item.endDate,<br>            displayOrder: item.displayOrder,<br>            createdAt: item.createdAt,<br>            updatedAt: item.updatedAt<br>        )<br>    }<br>}</pre><p>Want to add a simple notes: String? field to a habit?<br> You now have to edit:</p><ol><li>The Domain Item struct</li><li>The SDItem persistence model</li><li>The SDItemMapper</li><li>The SwiftDataItemStore save logic</li><li>The ItemFormViewModel</li><li>The test doubles (ItemStoreSpy)</li></ol><p>If you misspell a single field, SwiftData won’t save it, and compiler magic won’t save you.</p><p><strong>2. Building a Nuclear Reactor to Light a Candle<br></strong>Let’s be honest for a second: <strong>StreakOS is a habit tracker.</strong><br> You tap <strong>+</strong> until you reach 5 glasses of water, and the ring turns green.</p><p>Did I strictly need:</p><ul><li>An abstraction layer for DailyProgressLoader?</li><li>Dedicated ItemStoreSpy and DailyRecordStoreSpy test doubles?</li><li>An AppComposer dependency injection container on every target?</li></ul><p>Strictly speaking? <strong>Absolutely not.</strong> A junior developer could whip up a working version of this app in 250 lines of messy SwiftUI within an afternoon.</p><h4>⚖️ The Verdict: Over-Engineering or Essential?</h4><p>So, should you use Clean Architecture for your next Apple project?</p><pre><br>| Factor                         | Vanilla SwiftUI + @Query                  | Clean Architecture (Modular)              |<br>|--------------------------------|-------------------------------------------|-------------------------------------------|<br>| Speed to MVP / Hackathon       | Blazing fast (1-2 days)                   | Slow (Lots of setup boilerplate)          |<br>| Unit Test Execution            | Painful (Requires Simulator / Container)  | Instant (&lt; 500ms for 180+ tests)          |<br>| Multi-Platform (Mac/iOS/Watch) | High risk of spaghetti &amp; duplicate code   | Effortless (100% shared ViewModels)       |<br>| Framework Deprecation Risk     | High (Tied to Apple’s latest macro churn) | Zero (Domain logic is pure Swift)         |</pre><h3>My Rule of Thumb:</h3><ul><li><strong>Use Apple’s Vanilla SwiftUI if:</strong> You are building a solo, single-platform app, an MVP, or an app with simple CRUD screens where shipping this weekend is all that matters.</li><li><strong>Go Full Clean Architecture if:</strong> You are targeting multiple Apple platforms (macOS menu bar, watchOS, iOS), building complex offline sync rules (CloudKit), or working on a team where regression testing and instant CI pipelines are non-negotiable.</li></ul><p>Clean Architecture didn’t make building StreakOS faster upfront. But it gave me something far more valuable: <strong>complete confidence that my app won’t collapse like a house of cards the next time Apple releases a major OS update.</strong></p><p><em>Curious to inspect the code?</em></p><p>👉 <strong>Check out the repository on GitHub:</strong> <a href="https://github.com/aminfaruq/streakOS-project">aminfaruq/streakOS-project</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a164e735652" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsameday/clean-architecture-in-the-apple-ecosystem-over-engineering-masterclass-or-actually-useful-4a164e735652">Clean Architecture in the Apple Ecosystem: Over-Engineering Masterclass or Actually Useful?</a> was originally published in <a href="https://medium.com/devsameday">devsameday</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mengenal SwiftUI]]></title>
            <link>https://medium.com/gits-apps-insight/mengenal-swiftui-de511da0b4f2?source=rss-d416e2d282db------2</link>
            <guid isPermaLink="false">https://medium.com/p/de511da0b4f2</guid>
            <category><![CDATA[developer-stories]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Amin Faruq]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 10:10:24 GMT</pubDate>
            <atom:updated>2021-06-08T10:10:43.986Z</atom:updated>
            <content:encoded><![CDATA[<p>Apa itu SwiftUI dan bagaimana penerapannya?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9Qx-_oReedtEJctJ9bDNg.jpeg" /></figure><p>Sebagai iOS developer, ahli dalam membangun tampilan pada aplikasi berbasis iOS adalah hal yang penting. Biasanya kita sebagai iOS developer membangun layout memakai <strong>Storyboard</strong> ataupun <strong>programmatically,</strong> kini ada alternatif lain yang diperkenalkan oleh Apple. Dengan ini, kita jadi dimudahkan untuk membangun sebuah tampilan aplikasi iOS.</p><p>Menggunakan SwiftUI, selain membuat tampilan jadi lebih mudah, banyak pula benefit lainnya. Salah satu kemudahannya adalah mendukung <strong>Multi Platform Apple Device</strong>. Jadi, cukup satu kali coding, kita bisa membuat aplikasi ponsel berbasis iOS, macOS, iPadOS, hingga watchOS sekalipun.</p><p>Bagaimana, menarik bukan?</p><p><em>Baca selengkapnya tentang dasar SwiftUI di: </em><a href="https://gits.id/blog/tutorial-swiftui-basic-layout/"><strong><em>Tutorial SwiftUI — Mengenal Basic Layout</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de511da0b4f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gits-apps-insight/mengenal-swiftui-de511da0b4f2">Mengenal SwiftUI</a> was originally published in <a href="https://medium.com/gits-apps-insight">GITS Apps Insight</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>