<?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 Egzon Pllana on Medium]]></title>
        <description><![CDATA[Stories by Egzon Pllana on Medium]]></description>
        <link>https://medium.com/@egzonpllana?source=rss-73807a6a3e05------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AL8xOaghmU8C_6IfcJS83w.jpeg</url>
            <title>Stories by Egzon Pllana on Medium</title>
            <link>https://medium.com/@egzonpllana?source=rss-73807a6a3e05------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 14:58:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@egzonpllana/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[From 0 to over 1,000 Unit Tests: The DI Framework Behind It]]></title>
            <link>https://medium.com/@egzonpllana/from-0-to-over-1-000-unit-tests-the-di-framework-behind-it-9f0c167b6de9?source=rss-73807a6a3e05------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f0c167b6de9</guid>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Egzon Pllana]]></dc:creator>
            <pubDate>Thu, 07 May 2026 21:05:13 GMT</pubDate>
            <atom:updated>2026-05-07T21:31:50.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*PLfa7rvJGE8FfelPKmGl4Q.png" /></figure><p>If you’ve built an iOS app with more than three screens, you’ve felt the pain. You start passing dependencies through initializers, and it works — until your app graph gets deep enough that every view model needs six parameters, half of which exist only to forward them further down.</p><p>I’m the developer behind <a href="https://apps.apple.com/xk/app/engramr-reminders-alarms/id1506049485">Engramr — Reminders &amp; Alarms</a>, an app built with Clean Architecture across domain, data, and presentation layers. What started as clean init injection gradually turned into a wiring problem that Swift’s type system alone doesn’t solve.</p><p>So I built <a href="https://github.com/egzonpllana/orbitcore-ios">OrbitCore</a> — an open-source Swift Package that handles dependency registration, scoped resolution, thread-safe lazy injection, and test container swapping, with zero external dependencies. iOS 16+, Swift 6.0+.</p><p>This article is about why it exists and what problems it solves. For integration steps and code examples, check the <a href="https://github.com/egzonpllana/orbitcore-ios">GitHub repository</a>.</p><h3>The Five Problems That Pushed Me to Build This</h3><h3>1. Init Injection Doesn’t Scale</h3><p>Init injection is the textbook answer. And for two layers deep, it’s fine. But in a real app:</p><pre>let networkService = NetworkService()<br>let authService = AuthService(network: networkService)<br>let userService = UserService(network: networkService, auth: authService)<br>let loggingService = LoggingService()<br>let viewModel = UsersViewModel(userService: userService, logging: loggingService)<br>let view = UsersView(viewModel: viewModel)</pre><p>Now multiply that by 30 screens. Your composition root becomes a 200-line wiring file where every new dependency means touching ten lines. Add a parameter to NetworkService, and half the app&#39;s initialization chain breaks.</p><p>You’re not injecting dependencies. You’re manually threading a graph.</p><h3>2. Singletons Hiding in Plain Sight</h3><p>Most iOS projects eventually create a ServiceContainer or AppDependencies struct with static properties. It solves the wiring problem but introduces a worse one: every service lives forever.</p><pre>struct AppDependencies {<br>    static let networkService = NetworkService()<br>    static let userService = UserService()<br>    static let cacheService = CacheService()  // Lives forever. Why?<br>}</pre><p>There’s no lifecycle management. No way to say “this should exist only while someone needs it.” No way to tear down after logout. Everything is a singleton, whether it should be or not.</p><h3>3. Testing Requires Surgical Replacement</h3><p>Want to mock UserService in tests? With static singletons, you need conditional compilation flags, protocol witnesses with manual swapping, or a full test target that duplicates your composition root.</p><p>None of these are good. The first leaks test code into production. The second is fragile. The third doubles your maintenance surface.</p><h3>4. Lazy Properties Aren’t Thread-Safe</h3><p>Swift’s lazy var is not thread-safe. If two threads access an uninitialized lazy property simultaneously, you get double initialization — or worse, a crash. In a dependency injection context where services are resolved on first access, this is a real problem, not a theoretical one.</p><h3>5. No Scoping Means No Memory Strategy</h3><p>Should your analytics service live forever? Probably. Should a temporary image cache? Probably not. Without explicit scoping, every dependency has the same lifecycle: birth at registration, death at app termination.</p><p>You can’t express “keep this alive while someone references it, then release it automatically.” You can’t express “create a fresh instance every time.” You get one behavior — permanent — and hope for the best.</p><h3>The Journey: From Protocol to Container</h3><p>The first version was just ContainerProtocol — a protocol with register and resolve. Five lines of interface. It worked for hello-world examples but broke immediately under real conditions:</p><ul><li>Resolving a dependency inside a builder deadlocked the container</li><li>Concurrent access during app launch caused race conditions</li><li>No way to express lifecycle intent beyond “exists” and “doesn’t exist”</li></ul><p>The real shift happened when I asked: what if the container understood how long things should live?</p><p>Not just “registered” or “not registered.” Three explicit policies. You declare your intent, and the container enforces it.</p><h3>The Core Idea: Three Retain Policies, Zero Ambiguity</h3><p>Instead of one implicit lifecycle, OrbitCore gives you three explicit ones:</p><pre>// New instance every time. No caching. No sharing.<br>container.register(with: .default) { _ in<br>    UserService() as UserServiceProtocol<br>}<br><br>// Singleton. One instance for the container&#39;s lifetime.<br>container.register(with: .strong) { _ in<br>    LoggingService() as LoggingServiceProtocol<br>}<br>// Cached while referenced. Auto-released when nobody holds it.<br>container.register(with: .weak) { _ in<br>    TemporaryImageCache() as ImageCacheProtocol<br>}</pre><p>.default is for transient objects — view models, controllers, request-scoped services. Every resolve() call runs the builder fresh.</p><p>.strong is for true singletons — logging, analytics, network clients. One instance, cached in a dictionary, returned on every resolve.</p><p>.weak is the interesting one. It uses NSMapTable with .weakMemory value options. The container caches the instance, but holds it weakly. While your view controller or view model keeps a strong reference, the cache returns the same instance. The moment all external references are released, the entry auto-nils. Next resolve creates a fresh one.</p><p>No manual cache invalidation. No reference counting. The runtime handles it.</p><h3>Thread-Safe Resolution — Without Deadlocks</h3><p>This was the hardest problem, and the one most DI containers get wrong. Consider this registration:</p><pre>container.register(with: .strong) { container in<br>    let logger: LoggingServiceProtocol = try container.resolve()<br>    return UserService(logger: logger)<br>}</pre><p>The builder for UserService calls container.resolve() to get its dependency. If the container uses a simple NSLock, this deadlocks — the lock is already held by the outer resolve() call.</p><p>OrbitCore uses NSRecursiveLock. The same thread can acquire it multiple times without deadlocking. Nested resolution chains — no matter how deep — work correctly.</p><pre>private let lock = NSRecursiveLock()<br><br>public func resolve&lt;T&gt;() throws -&gt; T! {<br>    lock.lock()<br>    defer { lock.unlock() }<br>    // Resolution logic - may call resolve() again for dependencies<br>}</pre><p>Why NSRecursiveLock and not a dispatch queue or actor? Because resolution must be synchronous and re-entrant. Dispatch queues can&#39;t re-enter. Actors require async. A recursive lock is the precise tool for this problem.</p><h3>@Injected: One Line, Lazy, Thread-Safe</h3><p>The property wrapper is where most developers interact with OrbitCore:</p><pre>final class UsersViewModel {<br>    @Injected var userService: UserServiceProtocol<br>    @Injected var loggingService: LoggingServiceProtocol<br><br>    func fetchUsers() async {<br>        let users = try await userService.fetchUsers()<br>        loggingService.log(event: &quot;users_loaded&quot;)<br>    }<br>}</pre><p>No initializer parameters. No wiring. The container resolves each dependency on first access.</p><p>Under the hood, @Injected solves two problems:</p><p>Lazy resolution. Dependencies aren’t resolved at init time — they’re resolved on first property access via Swift’s lazy var. This means registration order doesn&#39;t matter, and circular dependencies don&#39;t crash at construction time.</p><p>Thread-safe first access. Swift’s lazy var isn&#39;t thread-safe. Two threads hitting an uninitialized @Injected property simultaneously could trigger double resolution. The wrapper guards access with NSLock:</p><pre>@propertyWrapper public class Injected&lt;T: Sendable&gt; {<br>    private let lock = NSLock()<br><br>    public var wrappedValue: T {<br>        lock.lock(); defer { lock.unlock() }<br>        return _wrappedValue<br>    }<br>    private lazy var _wrappedValue: T = {<br>        do {<br>            return try container.resolve()<br>        } catch {<br>            fatalError(error.localizedDescription)<br>        }<br>    }()<br>}</pre><p>Note: NSLock, not NSRecursiveLock. A property wrapper should never recursively access itself. Using the lighter lock is an intentional design choice — it&#39;s faster and makes invalid access patterns crash loudly instead of silently re-entering.</p><p>For eager resolution (resolve at init, not first access):</p><pre>@Injected(lazy: false) var analyticsService: AnalyticsServiceProtocol</pre><h3>Testing: Swap the Graph, Not the Code</h3><p>OrbitCore detects XCTest automatically:</p><pre>public extension ProcessInfo {<br>    static var isTesting: Bool {<br>        processInfo.environment[&quot;XCInjectBundleInto&quot;] != nil<br>            || processInfo.environment[&quot;XCTestConfigurationFilePath&quot;] != nil<br>            || processInfo.environment[&quot;XCTestSessionIdentifier&quot;] != nil<br>    }<br>}</pre><p>Your app’s entry point uses this to choose the dependency graph:</p><pre>init() {<br>    let container = Container()<br>    if ProcessInfo.isTesting {<br>        injectTestDependencies(into: container)<br>    } else {<br>        injectAllDependencies(into: container)<br>    }<br>    ContainerHolder.container = container<br>}</pre><p>No #if DEBUG. No build flags. No conditional compilation. The test target sets an environment variable that XCTest provides automatically. Production builds never see test code.</p><h3>The TestContainer Pattern</h3><p>For unit tests, OrbitCore’s protocol-based design enables a lightweight test container:</p><pre>final class TestContainer: ContainerProtocol {<br>    var dependencies: [Any] = []<br><br>    init(dependencies: [Any] = []) {<br>        self.dependencies = dependencies<br>    }<br>    func resolve&lt;T&gt;() throws -&gt; T! {<br>        dependencies.first(where: { $0 is T }) as? T<br>    }<br>    // resolveWithType, resolveAll, reset, register: trivial passthroughs over `dependencies`<br>}</pre><p>No factories. No builders. Just a flat array of pre-built instances. Combined with mock services that track calls via enum:</p><pre>final class MockUserService: UserServiceProtocol, @unchecked Sendable {<br>    private(set) var calls: [Call] = []<br><br>    enum Call: Equatable {<br>        case fetchUsers<br>        case fetchUser(identifier: String)<br>    }<br>    var fetchUsersResult: Result&lt;[UserDomainModel], Error&gt; = .success([])<br>    func fetchUsers() async throws -&gt; [UserDomainModel] {<br>        calls.append(.fetchUsers)<br>        return try fetchUsersResult.get()<br>    }<br>}</pre><p>With those two pieces in place — TestContainer and a mock with a Call enum — you verify behavior, call sequences, and side effects through Equatable assertions. The next section is what makes it scale.</p><h3>Unit Tests at Scale: The Helpers Behind 1,000+ Tests</h3><p>The TestContainer above is the foundation. What turns it into a suite that scales is three small helpers and a single design decision about where the seam lives.</p><p>Across two years and multiple apps and SDKs built on this pattern, the test count has crossed 1,000+. The reason it kept scaling — instead of buckling under setUp/tearDown overhead — is that adding test #1,001 costs the same as adding test #11.</p><h3>Three helpers, one seam</h3><pre>func createTestDependencies(_ dependencies: Any...) {<br>    ContainerHolder.container = TestContainer(dependencies: dependencies)<br>}<br><br>func removeTestDependencies() {<br>    ContainerHolder.container = nil<br>}<br><br>func insertTestDependencies(_ dependencies: Any...) {<br>    let existingContainer = ContainerHolder.container as? TestContainer<br>    let testContainer: TestContainer = existingContainer ?? .init()<br>    testContainer.dependencies.append(contentsOf: dependencies)<br>    ContainerHolder.container = testContainer<br>}</pre><p>Each test owns its own dependency graph. setUp calls createTestDependencies(mockA, mockB) to install a fresh TestContainer. tearDowncalls removeTestDependencies() to nil out ContainerHolder.container. insertTestDependencies is the escape hatch for tests that need to layer in an extra mock partway through, without rebuilding the graph.</p><p>Because the seam is a single static property — ContainerHolder.container — there&#39;s exactly one thing to swap. No scattered setMockA(...), setMockB(...), setMockC(...) calls. No accidental leakage from one test to the next. Tests can run in parallel and in any order because none of them share state with any other.</p><h3>A real ViewModel test</h3><p>This is what a typical test in the suite actually looks like — two mocks, state assertions, and call-sequence verification, all in one readable block:</p><pre>final class UsersViewModelTests: XCTestCase {<br>    private var mockUserService: MockUserService!<br>    private var mockLoggingService: MockLoggingService!<br>    private var sut: UsersViewModel!<br>    <br>    override func setUp() {<br>        super.setUp()<br>        mockUserService = MockUserService()<br>        mockLoggingService = MockLoggingService()<br>        sut = UsersViewModel(<br>            userService: mockUserService,<br>            loggingService: mockLoggingService<br>        )<br>    }<br><br>    override func tearDown() {<br>        removeTestDependencies()<br>        sut = nil<br>        mockLoggingService = nil<br>        mockUserService = nil<br>        super.tearDown()<br>    }<br><br>    func testFetchUsersSuccess() async {<br>        let expectedUsers = [<br>            UserDomainModel(identifier: &quot;1&quot;, name: &quot;Alice&quot;, email: &quot;alice@test.com&quot;),<br>            UserDomainModel(identifier: &quot;2&quot;, name: &quot;Bob&quot;, email: &quot;bob@test.com&quot;)<br>        ]<br>        mockUserService.fetchUsersResult = .success(expectedUsers)<br>        await sut.fetchUsers()<br>        XCTAssertEqual(sut.viewState, .loaded(expectedUsers))<br>        XCTAssertEqual(mockUserService.calls, [.fetchUsers])<br>        XCTAssertEqual(mockLoggingService.calls, [<br>            .log(event: &quot;users_screen_load&quot;, parameters: [:])<br>        ])<br>    }<br>}</pre><p>This particular SUT uses init injection, so the mocks go straight into the initializer and removeTestDependencies() is just hygiene. When the SUT instead uses @Injectedproperties, the only change is in setUp: call createTestDependencies(mockUserService, mockLoggingService) so the property wrappers resolve from the test graph. Same pattern, same helpers — the wiring path doesn&#39;t change the test.</p><h3>Why it scales</h3><p>Three earlier design choices in OrbitCore are doing the heavy lifting here:</p><ul><li>Protocol-first dependencies — every service is mockable by construction. No wrapping, no test-only subclasses, no @testable workarounds beyond what XCTest already gives you.</li><li>Flat-array TestContainer — no factories, no retain policies, no thread-safety plumbing in tests. Type-match lookup is enough because tests don&#39;t need lifecycle semantics.</li><li>ContainerHolder as a single seam — one swap point per test instead of scattered registrations across AppDelegate, view controllers, and child coordinators.</li></ul><p>Together, those three add up to the same boilerplate cost for every test in the suite. Adding test #1,001 takes the same time as adding test #11.</p><h3>Reset: Selective Teardown for Logout Flows</h3><p>User logs out. You need to clear every cached service — user data, session tokens, cached content — but keep infrastructure services alive: logging, analytics, crash reporting.</p><pre>container.reset(ignoreDependencies: [<br>    String(reflecting: LoggingServiceProtocol.self),<br>    String(reflecting: AnalyticsServiceProtocol.self)<br>])</pre><p>reset() clears all cached .strong and .weak instances. The ignoreDependenciesparameter takes type keys to preserve. Next resolve() for cleared types runs the builder fresh.</p><p>No app restart. No re-initialization of the entire graph. Surgical teardown.</p><h3>The Architecture: 7 Files, Zero Dependencies</h3><p>OrbitCore is a Swift Package with strict separation:</p><p>Core:</p><ul><li>ContainerProtocol — Public interface. 5 methods. Protocol-driven for testability.</li><li>Container — Default implementation. NSRecursiveLock, factory storage, three-policy resolution.</li><li>ContainerRetainPolicy — Enum: .default, .strong, .weak.</li><li>ContainerError — Single error case: .missingFactoryMethod. No overengineering.</li><li>ContainerHolder — Static singleton access point. nonisolated(unsafe) for Swift 6.</li></ul><p>Property Wrappers:</p><ul><li>@Injected — Lazy, thread-safe, Sendable-constrained resolution.</li></ul><p>Extensions:</p><ul><li>ProcessInfo.isTesting — XCTest environment detection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4_Kjq7T8cpdfM8XeHF9_A.png" /></figure><pre>@Injected → ContainerHolder → Container → Factory → Instance<br>                                  ↑              ↓<br>                                  └── resolve() ──┘  (recursive)</pre><p>The package knows nothing about your services. Your app registers its own types. The package just resolves them.</p><h3>Swift 6 Strict Concurrency: Already Compliant</h3><p>OrbitCore ships with full Swift 6 strict concurrency compliance:</p><ul><li>ContainerError: Sendable — errors can cross isolation boundaries</li><li>@Injected&lt;T: Sendable&gt; — generic constraint ensures resolved types are sendable</li><li>ContainerHolder uses nonisolated(unsafe) — required for static mutable state, with thread-safety managed by the caller</li><li>Test mocks use @unchecked Sendable — appropriate for test-only code</li></ul><p>No warnings. No workarounds. No @preconcurrency imports.</p><h3>Why NSMapTable for Weak Caching</h3><p>This is worth a section because most Swift developers haven’t used NSMapTable, and the weak caching behavior is the SDK&#39;s most elegant feature.</p><pre>private var weakInstances = NSMapTable&lt;NSString, AnyObject&gt;(<br>    keyOptions: [.copyIn],<br>    valueOptions: [.weakMemory]<br>)</pre><p>.weakMemory means the map table does not retain its values. When the last strong reference to a cached instance is released, the entry auto-nils. On next resolve(), the container finds nil, runs the builder fresh, and caches the new instance.</p><p>This is how you express “shared while needed, released when not” — without manual invalidation, timers, or reference counting. The Objective-C runtime does the bookkeeping for you.</p><p>Use case: an image processing pipeline that multiple view models share during a flow. While the flow is active, they share one instance. When the user navigates away and all view models are deallocated, the pipeline releases automatically. Next time someone needs it, a fresh one is created.</p><h3>String(reflecting:) — The Type Key Nobody Talks About</h3><p>How does the container know which factory to invoke for resolve&lt;UserService&gt;()?</p><pre>let key = String(reflecting: T.self)</pre><p>String(reflecting:) produces a fully qualified type name:</p><ul><li>String(reflecting: String.self) → &quot;Swift.String&quot;</li><li>String(reflecting: UserService.self) → &quot;MyApp.UserService&quot;</li><li>String(reflecting: Array&lt;String&gt;.self) → &quot;Swift.Array&lt;Swift.String&gt;&quot;</li></ul><p>It handles generics, nested types, and module namespacing. It’s deterministic and unique per type. No ObjectIdentifier, no custom hashing, no type erasure — just the type&#39;s canonical name as a string.</p><p>This also makes reset(ignoreDependencies:) work intuitively: you pass the same String(reflecting:) output to specify which types to preserve.</p><h3>Honest Downsides</h3><ul><li>Runtime resolution, not compile-time. If you forget to register a dependency, you find out at runtime, not compile time. The error is clear (ContainerError.missingFactoryMethod), but it&#39;s still a runtime failure.</li><li>Global state via ContainerHolder. The static container is convenient but is global mutable state. Thread-safety is the caller’s responsibility. Set it once at launch and don’t reassign.</li><li>No circular dependency detection. If Service A’s builder resolves Service B, and Service B’s builder resolves Service A, you get a stack overflow. The recursive lock prevents deadlock but not infinite recursion.</li><li>No scope hierarchies. There’s one container, not nested child containers.</li></ul><h3>Key Takeaways</h3><p>Declare lifecycle intent explicitly. Three retain policies eliminate the “everything is a singleton” trap. .default, .strong, .weak — pick one. Your future self will thank you.</p><p>Use NSRecursiveLock for nested resolution. Builders that resolve other dependencies are the common case, not the edge case. A simple lock deadlocks. A recursive lock handles it cleanly.</p><p>Lazy properties need their own lock. Swift’s lazy var is not thread-safe. If your property wrapper resolves lazily, guard first access with NSLock.</p><p>Detect tests via environment, not build flags.ProcessInfo.environment[&quot;XCInjectBundleInto&quot;] is set by XCTest automatically. No #if DEBUG needed.</p><p>Track mock calls with enums. enum Call: Equatable gives you precise, readable assertions on call sequences and parameters. Better than boolean flags or manual counters.</p><p>NSMapTable is underrated. .weakMemory value options give you automatic cache invalidation backed by the Objective-C runtime. Use it for any &quot;shared while needed&quot; pattern.</p><p>280 lines is enough. A DI container doesn’t need to be a framework. It needs to register, resolve, scope, and get out of the way.</p><p>The SDK is open-source: <a href="https://github.com/egzonpllana/orbitcore-ios">OrbitCore on GitHub</a>, with a full <a href="https://github.com/egzonpllana/orbitcore-ios/tree/main/OrbitCoreExampleiOS">example iOS app</a> showing the test helpers, mocks, and ViewModel patterns from this article. The full architecture ships in <a href="https://apps.apple.com/xk/app/engramr-reminders-alarms/id1506049485">Engramr — Reminders &amp; Alarms</a>, available on the App Store.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f0c167b6de9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built an Offline Photo Geocoding Engine That Clusters 8,000 Photos in Under 5 Seconds]]></title>
            <link>https://medium.com/@egzonpllana/how-i-built-an-offline-photo-geocoding-engine-that-clusters-8-000-photos-in-under-5-seconds-232917aae797?source=rss-73807a6a3e05------2</link>
            <guid isPermaLink="false">https://medium.com/p/232917aae797</guid>
            <category><![CDATA[geocoding]]></category>
            <category><![CDATA[kd-tree]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Egzon Pllana]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 10:23:19 GMT</pubDate>
            <atom:updated>2026-04-10T10:23:19.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRRbODosiiYV1kZbDmMtXA.png" /></figure><p>Apple’s CLGeocoder takes 1.3 seconds per request and is rate-limited to 50 requests per minute. For a photo organizer that needs to geocode thousands of photos and cluster them into trips by city, this meant waiting nearly 3 hours. So I replaced it with an embedded geographic database, a K-D Tree, and a chain expansion algorithm — all running offline in seconds.</p><p>This article covers every engineering decision: why brute force doesn’t work, how a spatial tree turns O(N) into O(log N), why “nearest city” isn’t enough, and how a chain algorithm captures an entire 5-day trip from a single seed photo.</p><h3>The Problem With CLGeocoder</h3><p>Apple provides CLGeocoder for reverse geocoding — converting GPS coordinates to city names. It works, but:</p><ul><li>Rate limited: 50 requests per 60 seconds, with a mandatory 1.3-second delay between calls</li><li>Max ~45 calls per session: After that, requests silently fail</li><li>Network dependent: Every call is a round-trip to Apple’s servers</li></ul><p>For a library with 8,000 photos producing 500+ event clusters, this meant 45+ seconds of geocoding with a two-phase UI approach (show placeholder names, then progressively resolve real ones). Users saw “Loading…” for nearly a minute. Unusable.</p><h3>The Solution: Embedded GeoNames + K-D Tree</h3><h3>The Dataset</h3><p><a href="https://geonames.org/">GeoNames</a> is an open geographic database. I use cities1000.txt — 167,000 cities worldwide with population &gt; 1,000. After trimming to only needed columns (name, latitude, longitude, country code, population), it compresses to a ~6MB TSV file embedded in the app bundle.</p><p>Why cities1000 and not cities15000 (33K cities, pop &gt; 15K)? The smaller dataset missed real cities. Bujanovac, Serbia (~18K residents) wasn&#39;t in it. Neither was Obiliq, Kosovo (12K). Photos in these cities resolved to the nearest larger city — often wrong. The 5x increase in dataset size (1.2MB → 6MB) is worth correct results worldwide.</p><h3>The K-D Tree: O(log N) Instead of O(N)</h3><p>A brute-force scan of 167K cities for the nearest one is O(N) per photo. With 8,000 photos, that’s 167K × 8K = 1.3 billion distance calculations. Even at nanosecond speeds, this takes seconds.</p><p>A K-D Tree (K-Dimensional Tree) partitions the 2D coordinate space into a binary tree. Finding the nearest neighbor takes O(log N) — about 17 comparisons instead of 167,000. Geocoding all 8,000 photos takes a few seconds total.</p><p>I use <a href="https://github.com/Bersaelor/KDTree">Bersaelor’s KDTree</a> Swift library, embedded directly in the package (no external dependency). Each city conforms to KDTreePoint with latitude/longitude as dimensions and Haversine distance for squaredDistance:</p><pre>struct GeoCityPoint: KDTreePoint {<br>    static let dimensions = 2<br>    <br>    func kdDimension(_ dimension: Int) -&gt; Double {<br>        dimension == 0 ? latitude : longitude<br>    }<br>    <br>    func squaredDistance(to other: GeoCityPoint) -&gt; Double {<br>        let dist = GeoUtils.distanceInKm(<br>            lat1: latitude, lng1: longitude,<br>            lat2: other.latitude, lng2: other.longitude<br>        )<br>        return dist * dist<br>    }<br>}</pre><p>The tree is built once at initialization (~100ms for 167K cities) and is immutable — no synchronization needed for concurrent reads.</p><h3>Why “Nearest City” Isn’t Enough: The Suburb Problem</h3><p>Pure nearest-neighbor geocoding produces results like “Lurup, Germany” instead of “Hamburg, Germany.” Lurup is a Hamburg district — its city center is closer to the photo’s coordinates than Hamburg’s center, so the K-D Tree returns it. But no user wants to see “Lurup” when they were in Hamburg.</p><p>The opposite problem exists too: Ferizaj (60K pop, standalone city) is 33km from Pristina (550K). A naive “pick the biggest city nearby” approach would incorrectly label Ferizaj photos as Pristina.</p><p>And a third edge case: GeoNames has bad population data for many small cities. Bujanovac shows population 0 despite having ~18K residents. A population-based heuristic would let Vranje (56K, 15km away) absorb it.</p><h3>The Three-Layer Heuristic</h3><p>The solution uses three checks:</p><ol><li>Distance: Only consider a parent city within 20km (suburbs are typically &lt; 20km from city center)</li><li>Population ratio: The parent must have 3x the population of the nearest city</li><li>Metropolis threshold: Only cities with population &gt; 100K can absorb neighbors</li></ol><p>The metropolis threshold is the key insight. It prevents small cities from absorbing each other regardless of population data quality. Only genuine metropolises (Hamburg, Pristina, Istanbul) absorb their suburbs. Two small neighboring cities always stay independent.</p><h3>Coordinate-Quantized Cache</h3><p>Photos taken at similar locations resolve to the same city. A cache keyed by quantized coordinates (~110m grid) avoids redundant suburb detection. For 200 Hamburg photos, only ~50 unique grid cells exist — 150 cache hits save nearestK(30) + distance calculations each.</p><h3>Smart Clustering: From Photos to Events</h3><p>Geocoding gives us city names. But we also need to group photos into discrete events — “Hamburg, May 9–12” and “Hamburg, June 3–5” should be separate trips, not one giant bucket.</p><h3>Phase 1: Time + Distance Splitting</h3><p>Photos are sorted by date and walked sequentially. A new cluster starts when:</p><ul><li>Time gap to previous photo &gt; 6 hours, OR</li><li>Distance to previous photo &gt; 50 km</li></ul><p>This naturally separates morning photos from evening photos (6h gap) and different cities visited the same day (50km distance).</p><h3>Phase 2: Same-Location Merging</h3><p>Consecutive clusters at the same quantized location (~111km grid) within 48 hours merge. This reconnects a multi-day stay: Day 1 Hamburg, sleep (6h gap), Day 2 Hamburg → one cluster.</p><h3>Phase 3: Post-Geocoding Merge</h3><p>After geocoding, clusters with the same resolved city name within 48h merge. Two clusters at different Hamburg coordinates both geocode to “Hamburg, Germany” → one event.</p><h3>Phase 4: Chain Rebuild with City Verification</h3><p>This is the critical step. After geocoding determines cluster names and anchor coordinates, each cluster’s photo set is rebuilt using a chain algorithm:</p><ol><li>Use the city center coordinates as the anchor (not a random photo’s GPS — prevents border-area photos from pulling in neighboring cities)</li><li>Find all library photos within 50km of the city center</li><li>Verify each photo geocodes to the same city name — a photo 45km from Hamburg center that’s actually closer to Bremen gets rejected</li><li>Chain with 24h gap (explained below)</li><li>Sweep no-GPS photos within the established date range</li></ol><p>The city-name verification is the key insight that prevents cross-city contamination. Without it, Pristina photos were appearing in Vranje events because they were within 50km of Vranje’s cluster anchor.</p><h3>The Pre-Computed Dictionary Optimization</h3><p>The naive approach — calling nearestCity() for each photo in each cluster&#39;s filter — is O(photos × clusters × log N). With 8K photos and 500 clusters, that&#39;s 4 million K-D Tree lookups.</p><p>Instead, I pre-compute a [localIdentifier: cityDisplayName] dictionary for ALL GPS photos once:</p><pre>8,000 photos × O(log 167K) = ~8,000 lookups ≈ 100ms</pre><p>The per-cluster filter then does a dictionary lookup — O(1). Total: O(M log N) pre-compute + O(M) per cluster, instead of O(M × C × log N). This turned a 30-second freeze into a 100ms operation.</p><h3>Chain Expansion: Capturing Entire Trips</h3><p>The original implementation used a fixed ±12-hour window around each event photo. Upload one photo from a 5-day Hamburg trip → only photos within 12 hours matched. 45 out of 163. Wrong.</p><h3>The Algorithm</h3><p>Chain expansion works like a flood fill on the time axis:</p><ol><li>Start with seed photos (event photo timestamps) marked as “included”</li><li>Forward pass: Walk the sorted timeline. If photo N is included and photo N+1 is within 24 hours → include N+1</li><li>Backward pass: Same, expanding left</li></ol><p>Each newly-included photo extends the chain. A 5-day trip where you took at least one photo per day chains together entirely from a single seed.</p><pre>Seed: May 9 21:17 (Hamburg port photo)<br>Chain forward:  May 9 → May 10 → May 11 → May 12 (no 24h gap)<br>Chain backward: May 9 → May 9 14:22 (arrival photos)<br>Result: May 9 14:22 to May 12 13:17 — entire trip captured</pre><h3>No-GPS Photo Sweep</h3><p>After the chain establishes the trip’s date range using GPS-confirmed photos, a final sweep includes photos without GPS (WhatsApp images, saved files, screenshots) that fall within that window. These couldn’t pass the location filter (no coordinates to verify), but they’re temporally anchored to the trip.</p><p>The screenshot toggle controls whether screenshots are included in this sweep.</p><h3>Performance Summary</h3><p>OperationComplexityReal-world timeK-D Tree build (167K cities)O(N log N)~100ms (once)Single geocode lookupO(log N)~0.01msPre-compute city names (8K photos)O(M log N)~100msPer-cluster chain filterO(M) dict lookup&lt;1msFull pipeline (8K photos → 500 events)O(M log N + M×C)~2–5 seconds</p><p>Compare to CLGeocoder: 45+ seconds for 45 lookups, then you’re rate-limited.</p><h3>The SDK</h3><p>The entire engine is extracted into a reusable Swift Package — <a href="https://github.com/egzonpllana/geo-clustering-ios">GeoClusteringSDK</a>. Zero external dependencies. Zero network calls. Fully offline.</p><pre>import GeoClusteringSDK<br><br>let sdk = GeoClusteringService()<br>let events = await sdk.clusterItems(itemMetadata) { phase in<br>    // Update UI with progress<br>}<br>// events = [GeoCluster(name: &quot;Hamburg, Germany&quot;, photoCount: 220, ...)]</pre><p>All parameters are configurable:</p><pre>var config = ClusteringConfiguration()<br>config.splitTimeThreshold = 6 * 3600      // 6h gap splits a cluster<br>config.chainGapSeconds = 24 * 3600        // 24h chain gap<br>config.suburbRadiusKm = 20               // Suburb detection radius<br>config.metropolisThreshold = 100_000      // Min pop to absorb suburbs<br>let sdk = GeoClusteringService(configuration: config)</pre><h3>Key Takeaways</h3><p>Replace network calls with embedded data when the dataset fits. 167K cities in 6MB is a reasonable tradeoff for instant, offline, unlimited geocoding.</p><p>K-D Trees make spatial search practical. O(log N) instead of O(N) is the difference between a few seconds and minutes of freezing.</p><p>Pre-compute what you’ll look up repeatedly. A dictionary built in 100ms saves millions of redundant tree traversals.</p><p>Nearest-neighbor isn’t enough for geocoding. Suburb detection needs distance + ratio + threshold. The metropolis threshold prevents bad data from corrupting results.</p><p>Chain expansion beats fixed windows. A flood-fill approach on sorted timestamps naturally captures multi-day trips from a single seed.</p><p>City-center anchoring prevents cross-contamination. Using the geocoded city’s coordinates (not a random photo’s GPS) as the chain anchor stops border-area photos from pulling in neighboring cities.</p><h3>References &amp; Links</h3><ul><li><a href="https://github.com/egzonpllana/geo-clustering-ios">GeoClusteringSDK</a> — the open-source Swift Package described in this article</li><li><a href="https://developer.apple.com/documentation/corelocation/clgeocoder">Apple CLGeocoder Documentation</a> — Apple’s built-in reverse geocoding API</li><li><a href="https://geonames.org/">GeoNames</a> — open geographic database providing the cities1000.txt dataset</li><li><a href="https://github.com/Bersaelor/KDTree">KDTree Swift Library</a> — K-D Tree implementation used for spatial search</li><li><a href="https://en.wikipedia.org/wiki/K-d_tree">K-D Tree (Wikipedia)</a> — background on the K-Dimensional Tree data structure</li><li><a href="https://en.wikipedia.org/wiki/Haversine_formula">Haversine Formula (Wikipedia)</a> — the distance formula used for geographic coordinate calculations</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=232917aae797" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Problems With NSLocalizedString That Made Me Build LocalizationEngine SDK]]></title>
            <link>https://medium.com/@egzonpllana/6-problems-with-nslocalizedstring-that-made-me-build-localizationengine-sdk-b1a393daaaf6?source=rss-73807a6a3e05------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1a393daaaf6</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Egzon Pllana]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 12:46:47 GMT</pubDate>
            <atom:updated>2026-03-08T16:39:04.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1-KEgFQkLurIuD_mdw1PQ.png" /></figure><p>If you’ve shipped an iOS app in more than one language, you know the pain. You start with NSLocalizedString, and it works — until it doesn&#39;t.</p><p>I’m the developer behind <a href="https://apps.apple.com/app/id1506049485">Engramr — Reminders and Alarms</a> app, an app that currently ships in 14 languages. What started as a straightforward localization setup gradually turned into a engineering problem that Apple’s built-in tools simply don’t solve.</p><p>So I built <a href="https://github.com/egzonpllana/localization-engine-ios">LocalizationEngine</a> — an open-source Swift Package that handles runtime language switching, OTA translation updates, pluralization, named substitutions, SwiftUI and UIKit support, with zero external dependencies. iOS 16+, Swift 5.9+.</p><p>This article is about why it exists and what problems it solves. For integration steps and code examples, check the <a href="https://github.com/egzonpllana/localization-engine-ios">GitHub repository</a>.</p><h3>The Six Problems That Pushed Me to Build This</h3><h4>1. Raw Strings Are Silent Landmines</h4><p>Every iOS developer has written this line:</p><pre>label.text = NSLocalizedString(&quot;home_reminders_tab&quot;, comment: &quot;&quot;)</pre><p>Now imagine a typo: &quot;home_remindrs_tab&quot;. No compiler error. No runtime crash. The user just sees the raw key on screen, and you won&#39;t know until someone reports it — or worse, until it shows up in an App Store screenshot.</p><p>Multiply that across 50 screens and hundreds of keys. You’re essentially programming with magic strings and hoping for the best.</p><h4>2. No Discoverability</h4><p>When a new team member joins, how do they find out what localization keys exist? They grep. There&#39;s no autocomplete, no single source of truth, no way to browse available strings by feature. It&#39;s archaeology, not engineering.</p><h4>3. Language Switching Requires an App Restart</h4><p>Apple’s Localizable.strings system resolves bundles at process launch. Want an in-app language picker? You&#39;re on your own. The system literally wasn&#39;t designed for it.</p><h4>4. Fixing a Typo Means Waiting for App Store Review</h4><p>You spot a translation error. A single wrong word in Japanese. The fix takes 10 seconds — but shipping it takes days. Your options? Wait for review, or pay $100–500/month for services like Lokalise or Phrase.</p><h4>5. Domain Logic Gets Polluted</h4><p>Your Category model shouldn&#39;t know about NSLocalizedString. But when a stored category named &quot;Work&quot; needs to display as &quot;Puna&quot; in Albanian, suddenly your domain layer is importing UIKit concepts. The boundary between storage and display starts leaking.</p><h4>6. You Can’t Test What You Can’t See</h4><p>How do you verify that every key has a translation in every supported language? How do you test that your domain localizers produce the right keys? With raw strings, you can’t — not meaningfully.</p><h4>The Journey: From Wrapper to Architecture</h4><p>The first version was embarrassingly simple: a wrapper around NSLocalizedString that loaded a different .lproj bundle based on a UserDefaults value. It worked for language switching, but it was fragile.</p><p>The real shift happened when I asked: what if invalid keys were impossible?</p><p>Not caught at runtime. Not flagged by a linter. Impossible to express in code.</p><p>That’s when the architecture clicked.</p><h4>The Core Idea: Make Invalid Keys Unrepresentable</h4><p>Instead of scattering string literals across your codebase, you define enums:</p><pre>enum CommonKey: String, CaseIterable {<br>    case cancel, close, delete, done, edit, save, today, tomorrow<br>}</pre><p>Try typing .cancl — it won&#39;t compile. The compiler is now your localization linter, for free.</p><p>Each feature area gets its own enum. A developer working on reminders only sees RemindersKey. No scrolling through 500 keys. Every key maps to a dot-separated string in your String Catalog: &quot;common.cancel&quot;, &quot;reminders.category_work&quot;.</p><p>At call sites, it looks like this:</p><pre>// SwiftUI<br>Text(L10n.settings.localized)<br>Button(L10n.done.localized) { ... }<br><br>// UIKit<br>label.text = L10n.settings.localized<br>cell.textLabel?.text = L10n.profile.localized</pre><p>.localized returns a plain String. No custom views. No wrappers. It works anywhere a String works.</p><h4>Live Language Switching — No Restart</h4><p>This was the feature that started the whole project. The SDK’s LocalizationManager is an ObservableObject with a @Published bundle property. When the user switches language:</p><ol><li>The new selection is persisted</li><li>The correct .lproj bundle is resolved</li><li>bundle publishes the change</li><li>SwiftUI re-renders every view that reads a localized string</li></ol><p>That’s it. No notification center plumbing. No manual refresh calls. SwiftUI’s reactive pipeline handles the propagation automatically. The entire app updates in a single frame.</p><p>For UIKit, the SDK provides LocalizationObserver — a closure that fires on the main thread whenever the language changes. Plug it into viewDidLoad, update your labels, done.</p><h4>OTA: Update Translations Without an App Release</h4><p>This is the headline feature, and the one that saves real money.</p><p>The idea is simple: upload .strings files to S3, a CDN, or any URL. The app downloads them on launch, caches to disk, and NSLocalizedString resolves from the cached bundle natively. If the download fails, bundled translations are the fallback.</p><p>You implement one protocol — TranslationFetchProviding — with your preferred networking stack. The SDK handles everything else: versioned disk caching, ETag conditional requests (skip re-download when nothing changed), minimum fetch intervals, parallel prefetch of multiple languages, and atomic writes.</p><p>No Lokalise. No Phrase. No Crowdin subscription. Your own S3 bucket and a 20-line fetch provider.</p><h4>The Bundle Caching Gotcha Nobody Tells You About</h4><p>Here’s a fun one I discovered the hard way: Apple’s Bundle class caches internally by file path. If you download a new translation and write it to the same path, Bundle happily serves the old cached version.</p><p>The SDK solves this by writing each download to a UUID-stamped subdirectory. Every update gets a fresh path, the old directory is cleaned up, and Bundle always sees new content. The entire operation is lock-protected to prevent race conditions during concurrent updates.</p><h4>What Happens When Things Go Wrong</h4><p>ScenarioBehaviorServer is downLast downloaded version from diskNever downloaded anythingBundled .strings from XcodeKey missing in active languageFalls back to English automaticallyNo internet on first launchBundled translations, OTA retries next launch</p><p>Users never see raw keys. The two-tier resolution — active bundle, then fallback language — guarantees it.</p><h4>Pluralization and Named Substitutions</h4><p>The SDK supports Apple’s native .stringsdict for plural rules:</p><pre>Text(L10n.itemsCount.localized(count: 1))  // &quot;1 item&quot;<br>Text(L10n.itemsCount.localized(count: 3))  // &quot;3 items&quot;</pre><p>Russian has 3 plural forms. Arabic has 6. You define them once in .stringsdict, and the system picks the right variant per locale.</p><p>For strings with multiple parameters, named tokens are more readable than positional %@:</p><pre>// &quot;Hello, %{name}! You have %{count} new messages.&quot;<br>Text(L10n.greeting.localized(substitutions: [<br>    &quot;name&quot;: &quot;Alice&quot;, &quot;count&quot;: &quot;5&quot;<br>]))</pre><p>Translators can rearrange %{name} and %{count} freely — they&#39;re order-independent.</p><h4>The Architecture: Five Modules, Zero Dependencies</h4><p>The SDK is a Swift Package split into focused modules with strict dependency direction:</p><ul><li>LocalizationCore — The engine: manager, protocols, bundle resolution, language switching. No UI framework dependency.</li><li>LocalizationSwiftUI — LocalizedText view and .localizationManager() environment modifier.</li><li>LocalizationUIKit — LocalizationObserver for reactive UIKit updates.</li><li>LocalizationOTA — Fetch, cache, and resolve OTA translations.</li><li>LocalizationEngine — Umbrella module. One import gives you everything.</li></ul><p>Every component is protocol-driven: bundle provider, storage backend, fetch provider, cache — all swappable. Swap UserDefaults for Keychain storage. Replace the main bundle provider with your OTA provider. Inject mocks for testing. The SDK doesn&#39;t care.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ToX8x-7pRL4SPsrDSGxw4w.png" /><figcaption><a href="https://github.com/egzonpllana/localization-engine-ios/blob/main/localize-engine-ios-diagram.png">https://github.com/egzonpllana/localization-engine-ios/blob/main/localize-engine-ios-diagram.png</a></figcaption></figure><pre>Views → Domain → LocalizationEngine → Foundation (nothing else)</pre><p>The package knows nothing about your app’s keys. Your app defines its vocabulary through enums. The package just resolves them.</p><h4>37 Tests That Actually Catch Things</h4><p>The test suite isn’t a checkbox exercise. Here’s what it catches:</p><ul><li>Typo in an enum raw value → Catalog sync test fails</li><li>Missing translation for a language → Parameterized language test fails</li><li>OTA cache miss → Integration test verifies bundled fallback</li><li>OTA V1 → V2 update → Integration test proves fresh data is served without restart</li><li>ETag conditional request → Integration test verifies skip on 304</li><li>Pluralization interpolation → Plural resolution test</li><li>Named substitution tokens → Substitution test</li><li>New key added without catalog entry → Catalog sync test catches it</li></ul><p>The OTA integration tests use real disk I/O and real NSLocalizedString resolution. No mocking the thing you&#39;re testing.</p><h4>What This Looks Like in Practice</h4><p>In <a href="https://apps.apple.com/app/engramr-reminders-alarms/id6504818693">Engramr</a>, adding a new language is:</p><ol><li>One enum case in AppLanguage</li><li>Translations in the String Catalog</li><li>Upload .strings to S3 for OTA</li></ol><p>That’s it. The picker updates automatically (thanks to CaseIterable). The resolution chain handles partial translations with English fallbacks. Remote Config can disable a language without an app update.</p><p>14 languages. Runtime switching. OTA updates. All from a single import LocalizationEngine.</p><h4>Honest Downsides</h4><ul><li>UserDefaults for persistence. Language preference is stored in UserDefaults. Works for single-user apps but isn&#39;t suitable for multi-profile scenarios.</li><li>OTA requires hosting. You need an S3 bucket or CDN, plus a type conforming to TranslationFetchProviding. The SDK handles caching and resolution — you handle hosting and networking.</li><li>Initial setup isn’t instant. Defining type-safe key enums takes more upfront work than throwing NSLocalizedString calls everywhere. The payoff is downstream: no typo bugs, full testability, instant discoverability.</li></ul><h4>Key Takeaways</h4><p>Make invalid keys unrepresentable. Enums are the cheapest static analysis you can add.</p><p>Treat localization as infrastructure. Put it in a package. Keep it key-agnostic. Let the app define its vocabulary.</p><p>@Published is all you need for live switching. Publish the bundle, SwiftUI handles the rest.</p><p>Always have a fallback. Two-tier resolution means users never see raw keys.</p><p>OTA doesn’t require a SaaS. A .strings file on S3, an ETag header, and a small protocol conformance. The SDK handles the rest.</p><p>Don’t let NSLocalizedString leak into your domain. Bridge stored data through dedicated localizer types that own the mapping.</p><p>Test behavior, not compilation. Catalog sync tests catch missing translations. OTA integration tests prove the full pipeline with real I/O.</p><p>The SDK is open-source: <a href="https://github.com/egzonpllana/localization-engine-ios">LocalizationEngine on GitHub</a>. The full architecture ships in <a href="https://apps.apple.com/us/app/engramr-reminders-alarms/id1506049485">Engramr — Reminders &amp; Alarms</a>, available on the App Store.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1a393daaaf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Apple App Attest for iOS API Security — No More Static Secrets]]></title>
            <link>https://levelup.gitconnected.com/implementing-apple-app-attest-for-ios-api-security-no-more-static-secrets-952014ed5058?source=rss-73807a6a3e05------2</link>
            <guid isPermaLink="false">https://medium.com/p/952014ed5058</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[certificate-attestation]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Egzon Pllana]]></dc:creator>
            <pubDate>Fri, 13 Feb 2026 22:14:09 GMT</pubDate>
            <atom:updated>2026-02-26T23:44:26.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Apple iOS App Attest — Egzon Pllana, image generated with Google Gemini" src="https://cdn-images-1.medium.com/max/1024/1*YJKlbXwF6gZWTl-CWJonKw.png" /></figure><h3>Why Static Secrets Don’t Work</h3><p>The most common approach to signing API requests in iOS apps is embedding a shared secret in the binary — an API key, an HMAC secret, a token. The app uses it to sign requests, the backend verifies the signature.</p><p>The problem: every device ships with the same secret. And that secret lives in app memory.</p><p>HMAC-SHA256 with XOR obfuscation? A determined attacker with Frida or Hopper extracts the XOR key and the obfuscated bytes in minutes. Encrypted plists, hardcoded strings, environment variables baked at build time — same story. If the secret exists in the binary, it can be read.</p><p>Once extracted, the attacker forges signed requests from any HTTP client. Your mobile app is bypassed entirely. Your backend thinks it’s talking to a real user.</p><p>The root cause isn’t weak obfuscation. It’s the shared secret model itself. Every device having the same key means compromising one device compromises all of them.</p><h3>App Attest: Per-Device Keys in Hardware</h3><p>Apple App Attest (DeviceCheck framework, iOS 14+) takes a fundamentally different approach. Instead of a shared secret, each device gets its own key pair:</p><ul><li>The private key is generated inside the Secure Enclave and never leaves. You cannot read it, export it, or copy it.</li><li>The public key is sent to your backend during a one-time attestation ceremony.</li><li>Every API request is signed with the device’s private key. The backend verifies using the stored public key.</li></ul><blockquote>A Secure Enclave is a dedicated hardware security processor inside Apple chips that isolates cryptographic operations and sensitive key material from the main CPU and operating system.</blockquote><p><strong>Shared Secret (HMAC)</strong></p><ul><li>Same static key embedded in every app binary</li><li>If reverse engineered once, the secret is exposed for all users</li><li>Anyone who knows the key can sign arbitrary requests</li><li>No built-in device authenticity verification</li></ul><p><strong>App Attest</strong></p><ul><li>Unique private key generated per device inside Secure Enclave</li><li>Key is hardware-bound and cannot be extracted</li><li>Monotonic counter prevents replay attacks</li><li>Apple verifies the device and the integrity of the app</li></ul><p>Compromising one device gives the attacker access to that device only. The key cannot be transferred.</p><h3>How It Actually Works (Who Does What, Where)</h3><h4>1. Key Generation</h4><p>On the app (device): When generateKey() is called, the Secure Enclave generates an asymmetric key pair:</p><ul><li>A private key (stored inside Secure Enclave).</li><li>A public key.</li></ul><p>The private key:</p><ul><li>Never leaves the device.</li><li>Cannot be exported.</li><li>Cannot be read from memory.</li></ul><p>At this point:</p><ul><li>Apple does not know about this key yet.</li><li>The backend does not know the public key yet.</li></ul><p>The app only receives a keyId that references the hardware-bound key.</p><h4>2. Attestation</h4><p>To prove the key is legitimate:<br><strong>On the backend:</strong></p><ul><li>A one-time nonce is generated.</li><li>A session ID is created to bind init and verify steps.</li></ul><p><strong>On the app:</strong></p><ul><li>The nonce is hashed.</li><li>attestKey(keyId, clientDataHash:) is called.</li></ul><p><strong>On Apple:</strong></p><ul><li>Apple verifies the device is genuine.</li><li>Apple verifies the app’s bundle ID and Team ID.</li><li>Apple creates a signed attestation object that includes:</li><li>The device’s public key</li><li>App identity</li><li>The nonce hash</li><li>Apple’s certificate chain</li></ul><p>Apple returns this attestation object to the app.</p><p><strong>On the app:</strong></p><ul><li>The attestation object and session ID are sent to the backend.</li></ul><p><strong>On the backend:</strong></p><ul><li>Apple’s certificate chain is validated locally.</li><li>Apple’s signature is verified locally.</li><li>The nonce is checked against the stored session.</li><li>The public key is extracted.</li><li>keyId → publicKey is stored.</li></ul><p>Apple is not contacted during backend validation. All verification is done locally using Apple’s root certificate.</p><p>After this step, the backend trusts that the stored public key belongs to a real device running your app.</p><h4>3. Assertion (Every API Request)</h4><p>After attestation, Apple is no longer involved.<br><strong>On the app:</strong></p><ul><li>A signing string is built (method, path, timestamp, body).</li><li>The hash of that string is signed using the private key inside Secure Enclave.</li><li>The app sends:</li><li>X-Key-ID</li><li>X-Signature</li><li>X-Timestamp</li></ul><p><strong>On the backend:</strong></p><ul><li>The stored public key is loaded using X-Key-ID.</li><li>The same signing string is rebuilt.</li><li>The signature is verified using the public key.</li><li>The monotonic counter is checked to prevent replay.</li></ul><p>If verification succeeds, the request is accepted.</p><h3>Architecture</h3><p>We followed Clean Architecture with three layers:</p><pre>Domain/<br>  AppAttestState.swift          — State enum<br>  AppAttestError.swift          — Error enum<br>  AppAttestServicing.swift      — Protocol<br>Data/<br>  AppAttestKeyStoring.swift     - Keychain protocol<br>  KeychainAppAttestRepository.swift - Keychain implementation<br>Infrastructure/<br>  AppAttestService.swift                    - Actor (attestation lifecycle)<br>  AppAttestRequestSigningInterceptor.swift  - Signs every request<br>  AttestationGatingInterceptor.swift        - Blocks requests until attested</pre><p>The Domain layer defines the contract. The Data layer handles persistence. The Infrastructure layer does the actual work. No layer reaches into another — dependencies point inward.</p><h3>Attestation: One-Time Per Device</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNA1ZZZ4puu4FySsVgxWSw.png" /></figure><p>Attestation runs automatically on app launch. It establishes trust between the device and the backend.</p><pre>actor AppAttestService: AppAttestServicing {<br>    private var currentState: AppAttestState = .idle<br>    private let keyStore: AppAttestKeyStoring<br>    <br>  func beginAttestation() async {<br>        guard case .idle = currentState else { return }<br>        // Already attested in a previous session?<br>        if let storedKeyId = keyStore.readKeyId() {<br>            currentState = .attested(keyId: storedKeyId)<br>            return<br>        }<br>        guard DCAppAttestService.shared.isSupported else {<br>            currentState = .failed(.attestationFailed)<br>            return<br>        }<br>        currentState = .attesting<br>        await performAttestation()<br>    }<br>}</pre><p>If a key ID exists in the Keychain, we skip everything — zero network calls, zero Apple server hits. The device was already attested.</p><p>For first-time attestation:</p><pre>private func performAttestation() async {<br>    do {<br>        // 1. Generate key pair in Secure Enclave<br>        let keyId = try await DCAppAttestService.shared.generateKey()<br>        // 2. Get a challenge nonce and session ID from our backend<br>        let nonceResult = try await fetchNonce()<br>        // 3. Ask Apple to attest this key<br>        let nonceHash = Data(SHA256.hash(data: Data(nonceResult.nonce.utf8)))<br>        let attestation = try await DCAppAttestService.shared.attestKey(<br>            keyId,<br>            clientDataHash: nonceHash<br>        )<br>        // 4. Backend validates with Apple, extracts keyID, stores public key<br>        try await verifyWithBackend(<br>            sessionId: nonceResult.sessionId,<br>            attestation: attestation<br>        )<br>        // 5. Persist key ID in shared Keychain<br>        keyStore.writeKeyId(keyId)<br>        currentState = .attested(keyId: keyId)<br>    } catch {<br>        currentState = .failed(.attestationFailed)<br>    }<br>}</pre><p>Step by step:</p><ol><li>The Secure Enclave generates a key pair. The private key stays in hardware.</li><li>The backend generates a one-time nonce and a session ID that links the init and verify steps (prevents replay of attestation objects).</li><li>Apple’s attestation service verifies the device is real and the app is legitimate, then returns a signed attestation object containing the public key.</li><li>The backend receives the session ID and attestation object, validates the attestation against Apple’s root certificate, checks the nonce matches via the session, and extracts and stores the public key.</li><li>The key ID is persisted in the Keychain with a shared access group (so the Share Extension can use it too).</li></ol><h3>Request Signing: Every API Call</h3><p>Once attested, every request is signed transparently via a network interceptor:</p><pre>struct AppAttestRequestSigningInterceptor: NetworkInterceptorProtocol {<br>    private let appAttestService: AppAttestServicing<br><br>    func interceptAsync(request: URLRequest) async throws -&gt; URLRequest {<br>        var signedRequest = request<br>        guard let keyId = await appAttestService.keyId else {<br>            throw AppAttestError.notAttested<br>        }<br>        let timestamp = ISO8601DateFormatter().string(from: Date())<br>        let method = (request.httpMethod ?? &quot;GET&quot;).uppercased()<br>        let path = extractPath(from: request)<br>        let body = request.httpBody.flatMap {<br>            String(data: $0, encoding: .utf8)<br>        } ?? &quot;&quot;<br>        // Build signing string<br>        let signingString = &quot;\(method)|\(path)|\(timestamp)|\(body)&quot;<br>        let clientDataHash = Data(SHA256.hash(data: Data(signingString.utf8)))<br>        // Sign with Secure Enclave private key<br>        let assertion = try await appAttestService.generateAssertion(<br>            clientDataHash: clientDataHash<br>        )<br>        signedRequest.setValue(<br>            assertion.base64EncodedString(),<br>            forHTTPHeaderField: &quot;X-Signature&quot;<br>        )<br>        signedRequest.setValue(timestamp, forHTTPHeaderField: &quot;X-Timestamp&quot;)<br>        signedRequest.setValue(keyId, forHTTPHeaderField: &quot;X-Key-ID&quot;)<br>        return signedRequest<br>    }<br>}</pre><p>The signing string METHOD|path|timestamp|body covers all mutable parts of the request. The backend uses the X-Key-ID header to look up the stored public key, rebuilds the same signing string, and verifies the assertion.</p><p>No ViewModel, UseCase, or Repository knows this is happening. The interceptor handles it at the network layer.</p><h3>Gating: No Unsigned Requests</h3><p>A separate interceptor blocks all API calls until attestation completes:</p><pre>struct AttestationGatingInterceptor: NetworkInterceptorProtocol {<br>    private let appAttestService: AppAttestServicing<br><br>    func interceptAsync(request: URLRequest) async throws -&gt; URLRequest {<br>        // Attest endpoints are exempt (pre-attestation)<br>        if request.url?.path.contains(&quot;/apple/attest&quot;) == true {<br>            return request<br>        }<br>        _ = try await appAttestService.awaitAttestation()<br>        return request<br>    }<br>}</pre><p>If the user taps “Sign In” while attestation is in progress, the request waits. The loader spinner already covers the UX. Once attested, the request proceeds and gets signed.</p><p>If attestation failed, the request throws — it is never sent. No unsigned request can reach the backend.</p><h3>Interceptor Chain Order</h3><p>Both interceptors plug into the existing chain:</p><pre>func makeAuthorized() -&gt; APIClient {<br>    APIClient(interceptors: [<br>        NetworkAwareInterceptor(networkMonitor: networkMonitor),<br>        AttestationGatingInterceptor(appAttestService: appAttestService),<br>        TokenRefreshingInterceptor(),<br>        AuthInterceptor(tokenProvider: { self.tokenRepository.accessToken }),<br>        AppAttestRequestSigningInterceptor(appAttestService: appAttestService),<br>        RetryInterceptor(maxRetries: 3)<br>    ])<br>}</pre><ol><li>NetworkAware — check connectivity</li><li>AttestationGating — block until attested</li><li>TokenRefreshing — handle 401s / token expiry</li><li>Auth — add Bearer token</li><li>AppAttestRequestSigning — sign the final request</li><li>Retry — retry on failure (re-signs with fresh timestamp)</li></ol><p>Signing comes after auth so the request is in its final form. Retry comes last so failed requests get re-signed with a new timestamp.</p><h3>Why EventHorizon Made This Easy</h3><p>The networking layer is built on <a href="https://github.com/egzonpllana/event-horizon-ios">EventHorizon</a>, a Swift networking library I built. EventHorizon provides a NetworkInterceptorProtocol with both sync and async variants — interceptors can modify outgoing requests, inspect incoming responses, and throw errors to abort the pipeline.</p><p>Adding App Attest meant writing two structs that conform to this protocol and inserting them into the existing interceptor array. The gating interceptor blocks requests until attestation completes. The signing interceptor signs them with the Secure Enclave.</p><p>No existing code was modified. No ViewModel, UseCase, or Repository was touched. The entire security layer was added at the network transport level, invisible to everything above it.</p><h3>Concurrent Waiters</h3><p>Multiple API calls might fire while attestation is still in progress. The actor uses a continuation-based pattern to handle this:</p><pre>private var waitingContinuations: [UUID: CheckedContinuation&lt;String, any Error&gt;] = [:]<br>    func awaitAttestation() async throws -&gt; String {<br>      switch currentState {<br>      case .attested(let keyId):<br>          return keyId<br>      case .failed(let error):<br>          throw error<br>      case .attesting:<br>          return try await waitForAttestation()<br>      case .idle:<br>          throw AppAttestError.notAttested<br>    }<br>}<br><br>private func waitForAttestation() async throws -&gt; String {<br>    let waiterId = UUID()<br>    return try await withCheckedThrowingContinuation { continuation in<br>        waitingContinuations[waiterId] = continuation<br>        Task {<br>            try? await Task.sleep(nanoseconds: UInt64(30.0 * 1_000_000_000))<br>            timeoutWaiter(waiterId)<br>        }<br>    }<br>}</pre><p>All waiters are resumed at once when attestation completes — success or failure. The 30-second timeout prevents indefinite blocking.</p><p>Actor isolation guarantees thread safety without locks or queues.</p><h3>Share Extension</h3><p>The key ID is stored in a shared Keychain access group. When the Share Extension launches, it reads the stored key ID and skips straight to .attested. Same Secure Enclave key pair, no re-attestation. The extension signs requests identically to the main app.</p><h3>Backend: Two Endpoints Required</h3><p>App Attest is not iOS-only — the backend needs two new endpoints to complete the attestation handshake:</p><p>POST /apple/attest-init — Returns a session ID and a one-time server-generated <strong>nonce</strong>. The session ID links this init request to the subsequent verify request. The app includes the nonce in the attestation request to Apple. Without it, an attacker could capture a valid attestation object and replay it. The nonce proves the attestation is fresh. Store it server-side with a short TTL (e.g. 60 seconds).</p><p>POST /apple/attest — Receives the session ID and the Base64-encoded CBOR attestation object. The backend uses the session ID to retrieve the nonce, validates the attestation against Apple’s root certificate, checks the nonce matches, and extracts the public key and key ID from the attestation.</p><p>The public key is stored mapped to the key ID. From this point on, the backend uses it to verify every assertion the device sends in X-Signature.<br>Both endpoints must be unsigned — the device hasn’t completed attestation yet, so it can’t sign requests. All other endpoints require three headers: <br>X-Signature (the assertion), <br>X-Timestamp (RFC 3339 UTC), and <br>X-Key-ID (the device’s key identifier).</p><h3>Why No Fallback</h3><p>It would be easy to add an HMAC fallback for devices that don’t support App Attest. We chose not to.</p><p>If you ship a fallback signing mechanism alongside App Attest, an attacker will simply trigger the fallback path. The static secret is still in the binary. You’ve added complexity without adding security.</p><p>If a device can’t attest, it can’t use the API. That’s the point.</p><h3>Key Takeaways</h3><ul><li>Static shared secrets are fundamentally broken. XOR, encryption, obfuscation — they slow attackers down, they don’t stop them. The problem is the shared secret model, not the obfuscation technique.</li><li>App Attest moves the private key into hardware. The Secure Enclave is a different trust boundary than app memory. The key cannot be read or exported.</li><li>The interceptor pattern makes signing transparent. Business logic doesn’t know about attestation. Network layer handles it.</li><li>Actors are the right tool for attestation state. Single attestation, multiple waiters, timeout handling — thread-safe by design, no manual locking.</li><li>No fallback is a security decision, not a limitation. A fallback path is an attack surface.</li></ul><h3>References</h3><ul><li><a href="https://developer.apple.com/videos/play/wwdc2021/10244/">Safeguard your accounts, devices, and transactions</a> — WWDC21 session covering App Attest, DeviceCheck, and fraud prevention strategies.</li><li><a href="https://developer.apple.com/documentation/devicecheck/establishing-your-app-s-integrity">Establishing Your App’s Integrity</a> — Apple’s main walkthrough for implementing App Attest on the client side.</li><li><a href="https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server">Validating Apps That Connect to Your Server</a> — Backend verification guide for validating attestation objects and assertions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=952014ed5058" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/implementing-apple-app-attest-for-ios-api-security-no-more-static-secrets-952014ed5058">Implementing Apple App Attest for iOS API Security — No More Static Secrets</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Network Chaos ️ to Cached Harmony]]></title>
            <link>https://medium.com/@egzonpllana/from-network-chaos-%EF%B8%8F-to-cached-harmony-5fce28b199b5?source=rss-73807a6a3e05------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fce28b199b5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Egzon Pllana]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 07:42:08 GMT</pubDate>
            <atom:updated>2025-08-11T07:42:08.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4Jl3BHKWU6sLHkIJOkNFA.png" /></figure><h3>The Problem: Network Request Hell</h3><p>Picture this: You’re building a social app where users need to invite contacts to different features, start chats, create groups, and share content. Initially, every screen that needed contact data was making its own API call:</p><pre>// The old way - scattered across multiple ViewModels<br>class InviteFriendsViewModel: ObservableObject {<br>    func loadContacts() {<br>        // Direct API call every time<br>        apiClient.fetchContacts { contacts in<br>            self.contacts = contacts<br>        }<br>    }<br>}<br><br>class ChatCreationViewModel: ObservableObject {<br>    func loadContacts() {<br>        // Another API call for the same data!<br>        apiClient.fetchContacts { contacts in<br>            self.contacts = contacts<br>        }<br>    }<br>}<br><br>class ShareContentViewModel: ObservableObject {<br>    func loadContacts() {<br>        // Yet another redundant API call...<br>        apiClient.fetchContacts { contacts in<br>            self.contacts = contacts<br>        }<br>    }<br>}</pre><p>The result? Unnecessary network traffic, slower user experience, increased server load, inconsistent data states, and poor offline behavior. Users would see loading spinners everywhere, and the same contact data was being fetched multiple times within seconds.</p><h3>The Solution: A Multi-Layered Caching Architecture</h3><p>I completely redesigned the contact data flow using Clean Architecture principles, introducing several key layers:</p><ol><li>Repository Layer — Single source of truth with in-memory caching</li><li>Use Case Layer — Business logic coordination</li><li>Signal Service — Event-driven cache invalidation</li><li>Cache Management Service — Centralized cache lifecycle</li><li>Reactive Publishers — Real-time UI updates</li></ol><p>Let’s dive into each layer:</p><h4>Layer 1: The Repository — Your Data’s Single Source of Truth</h4><p>The ContactsRepository is where the magic begins. It maintains an in-memory cache and decides whether to serve cached data or fetch fresh data:</p><pre>final class ContactsRepository: ContactsRepositoryProtocol, ObservableLoggableObject {<br>    <br>    // In-memory cache - the star of the show<br>    @Published private(set) var contacts: ContactsResponseDomainModel = .init(<br>        contacts: [],<br>        contactRequestsSent: [],<br>        contactRequestsReceived: [],<br>        placeholderContacts: []<br>    )<br>    <br>    @Published private(set) var isLoading: Bool = false<br>    @Published private(set) var error: Error?<br>    <br>    private var hasLoadedData = false<br>    <br>    // Smart fetching logic<br>    func fetchContacts() async -&gt; ContactsResponseDomainModel {<br>        if !hasLoadedData {<br>            return await refreshContacts() // First time? Fetch from network<br>        }<br>        return contacts // Already have data? Return cache instantly<br>    }<br>    <br>    @MainActor<br>    func refreshContacts() async -&gt; ContactsResponseDomainModel {<br>        isLoading = true<br>        error = nil<br>        <br>        do {<br>            let contactsDTO: ContactsResponseDTO = try await apiClient.request(<br>                APIEndpoint.fetchContacts<br>            )<br>            <br>            let allContacts: ContactsResponseDomainModel = contactsDTO.toDomainModel()<br>            <br>            self.contacts = allContacts<br>            self.hasLoadedData = true<br>            self.isLoading = false<br>            <br>            return allContacts<br>        } catch {<br>            self.error = error.mapTo(ContactsError.server)<br>            self.isLoading = false<br>            return contacts // Return cached data even on error<br>        }<br>    }<br>}</pre><p>Key Benefits:</p><ul><li>Instant subsequent loads: After the first fetch, all other screens get data immediately</li><li>Offline resilience: Cached data remains available even when network fails</li><li>Loading state management: Centralized loading states prevent UI flickering</li></ul><h4>Layer 2: The Use Case — Business Logic Orchestration</h4><p>The ContactsUseCase sits between the repository and presentation layer, handling business rules:</p><pre>final class ContactsUseCase: ContactsUseCaseProtocol {<br>    <br>    @Injected private var contactsRepository: ContactsRepositoryProtocol<br>    <br>    // Expose repository publishers to ViewModels<br>    lazy var contactsPublisher: AnyPublisher&lt;ContactsResponseDomainModel, Never&gt; = {<br>        contactsRepository.contactsPublisher<br>    }()<br>    <br>    lazy var isLoadingPublisher: AnyPublisher&lt;Bool, Never&gt; = {<br>        contactsRepository.isLoadingPublisher<br>    }()<br>    <br>    // Business logic for contact actions<br>    func acceptContactRequest(from userID: String) async throws {<br>        try await contactsRepository.acceptContactRequest(from: userID)<br>        // Repository automatically signals refresh via SignalService<br>    }<br>    <br>    func deleteContact(userID: String) async throws {<br>        try await contactsRepository.deleteContact(userID: userID)<br>    }<br>}</pre><p>This layer ensures that:</p><ul><li>ViewModels don’t directly depend on repositories</li><li>Business rules are centralized</li><li>Testing becomes easier with clear boundaries</li></ul><h3>Layer 3: The Signal Service — Event-Driven Cache Invalidation</h3><p>Here’s where it gets really interesting. The SignalService broadcasts events when contact data changes, ensuring all parts of the app stay synchronized:</p><pre>final class SignalService: SignalServicing {<br>    <br>    private let contactsListNeedsReloadSubject = PassthroughSubject&lt;Void, Never&gt;()<br>    <br>    lazy var contactsListNeedsReloadPublisher: AnyPublisher&lt;Void, Never&gt; = {<br>        contactsListNeedsReloadSubject.eraseToAnyPublisher()<br>    }()<br>    <br>    func signalContactsListNeedsReload() {<br>        contactsListNeedsReloadSubject.send()<br>    }<br>}</pre><p>Every contact action triggers a signal:</p><pre>// In ContactsRepository<br>func acceptContactRequest(from userID: String) async throws {<br>    try await apiClient.request(<br>        APIEndpoint.patchContactAction(userID: userID, action: .accept)<br>    )<br>    // This line ensures all screens get fresh data<br>    signalService.signalContactsListNeedsReload()<br>}</pre><p>The repository listens for these signals and automatically refreshes:</p><pre>// In ContactsRepository.init() add the observer<br>private func setupSignalObserver() {<br>    signalService.contactsListNeedsReloadPublisher<br>        .sink { [weak self] in<br>            Task { @MainActor in<br>                self?.log(&quot;Received signal to reload contacts&quot;)<br>                _ = await self?.refreshContacts()<br>            }<br>        }<br>        .store(in: &amp;cancellables)<br>}</pre><p>The Beautiful Result: When a user accepts a contact request in one screen, every other screen showing contacts automatically updates without any additional API calls!</p><h4>Layer 4: Centralized Cache Management</h4><p>The CacheManagementService provides a single point to clear all caches when needed (like user logout):</p><pre>final class CacheManagementService: CacheManagementServicing {<br>    <br>    @Injected private var contactsRepository: ContactsRepositoryProtocol<br>    @Injected private var userProfileRepository: UserProfileRepositoryProtocol<br>    // ... other repositories<br>    <br>    func clearAllCaches() {<br>        log(&quot;Clearing all application caches&quot;)<br>        <br>        contactsRepository.clearCache()<br>        userProfileRepository.clearCache()<br>        remoteImageService.clearCache()<br>        <br>        log(&quot;Successfully cleared all application caches&quot;)<br>    }<br>}</pre><h4>Layer 5: Reactive ViewModels</h4><p>ViewModels now become much simpler and more reactive:</p><pre>final class ContactsListViewViewModel: ObservableObject {<br>    <br>    @Injected private var contactsUseCase: ContactsUseCaseProtocol<br>    @Published var myContacts: [ContactDomainModel] = []<br>    @Published var viewState: ViewState = .idle<br>    <br>    init() {<br>        setupObservers()<br>    }<br>    <br>    private func setupObservers() {<br>        // React to data changes automatically<br>        contactsUseCase.contactsPublisher<br>            .sink { [weak self] contacts in<br>                self?.updateContactsData(contacts)<br>            }<br>            .store(in: &amp;cancellables)<br>        <br>        // React to loading state changes<br>        contactsUseCase.isLoadingPublisher<br>            .sink { [weak self] isLoading in<br>                self?.viewState = isLoading ? .loading : .loaded<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>    <br>    func onAppear() {<br>        if !hasLoadedData {<br>            fetchContacts() // Only fetches if no cached data<br>        }<br>    }<br>}</pre><h3>The Results: Before vs After</h3><h4>Before: Network Request Hell</h4><ul><li>API Calls: 5–10 calls per user session for the same data</li><li>Loading Time: 2–3 seconds per screen</li><li>Network Usage: High and redundant</li><li>User Experience: Constant loading spinners</li><li>Offline Support: None</li></ul><h4>After: Cached Harmony</h4><ul><li>API Calls: 1 initial call + event-driven refreshes only</li><li>Loading Time: Instant for subsequent screens</li><li>Network Usage: Reduced by ~80%</li><li>User Experience: Smooth, responsive UI</li><li>Offline Support: Full cached data availability</li></ul><h4>Why This Architecture is Special</h4><ol><li>Performance: Dramatic reduction in network calls</li><li>Consistency: Single source of truth ensures data consistency</li><li>Scalability: Easy to add new features without API changes</li><li>Maintainability: Clear separation of concerns</li><li>Testability: Each layer can be tested independently</li><li>User Experience: Instant subsequent loads, smooth interactions</li><li>Offline Support: Graceful degradation when network is unavailable</li></ol><h4>Key Takeaways</h4><p>This architecture transforms a common iOS app problem into a competitive advantage. By implementing proper caching with reactive updates, you get:</p><ul><li>Better performance with fewer network requests</li><li>Improved user experience with instant loads</li><li>Reduced server costs through decreased API usage</li><li>More maintainable code with clear architectural boundaries</li><li>Better offline support with cached data availability</li></ul><p>The investment in building these foundational layers pays dividends across your entire application. Every new feature that needs contact data gets these benefits for free, and your users get a consistently fast, smooth experience.</p><p><em>The best part? This pattern is reusable across any data type in your app — contacts, user profiles, settings, media, you name it!</em></p><h4>That was it! 🚀</h4><p>Thank you for diving into this article on building stronger app layers with Clean Architecture in mind. I hope it’s inspired you to explore the finer details of this powerful approach and how it can transform your projects. Until next time — keep crafting clean, scalable code!</p><h3>Let’s Connect</h3><ul><li>LinkedIn: <br><a href="https://www.linkedin.com/in/egzon-pllana">https://www.linkedin.com/in/egzon-pllana</a></li><li>GitHub: <br><a href="https://github.com/egzonpllana">https://github.com/egzonpllana</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fce28b199b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Stopped a Silent Memory Leak in My iOS App]]></title>
            <link>https://medium.com/@egzonpllana/how-i-stopped-a-silent-memory-leak-in-my-ios-app-282aef170df5?source=rss-73807a6a3e05------2</link>
            <guid isPermaLink="false">https://medium.com/p/282aef170df5</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Egzon Pllana]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 15:12:20 GMT</pubDate>
            <atom:updated>2025-08-04T20:37:41.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*DVBP3FA4mMOicrRPwxhC1A.jpeg" /></figure><p>Memory Profiler SDK: <a href="https://github.com/egzonpllana/memory-profiler-ios">https://github.com/egzonpllana/memory-profiler-ios</a></p><blockquote>While reviewing one of my personal iOS apps over the weekend, I uncovered a memory issue that had gone unnoticed: a memory leak that <strong>was silently eating away at system resources</strong>. What started as a casual check turned into a deep dive into memory profiling, optimization techniques, and eventually… an open-source service others can now benefit from.</blockquote><p>Let me take you through the journey of how I went from achieving <strong>85% memory reduction on a common user interaction</strong>.</p><h4>💥 The Problem</h4><p>While casually exploring the app, I noticed something off: the RAM footprint would <strong>jump 10–15MB with every tab switch</strong>. Ten minutes of typical usage and memory bloated from <strong>196MB to over 300MB</strong>. No downward trend. Just continuous accumulation.</p><p>That’s a massive red flag for memory leaks — especially in production-grade apps where memory pressure can quickly become app-killer territory.</p><p>Here’s a breakdown of what I was seeing:</p><ul><li>🧠 <strong>196MB</strong> baseline memory on cold launch</li><li>🔁 <strong>+10–15MB</strong> per tab switch</li><li>⏱️ After 10 mins: <strong>~310MB+</strong> and growing</li></ul><p>It wasn’t a single bug. It was a pattern. And I needed a systemic solution.</p><h4>🛠️ Diagnosis</h4><p>After digging deeper with Instruments, I confirmed what I suspected:</p><ul><li>Views weren’t being deallocated.</li><li>Combine subscriptions weren’t canceled.</li><li>Timers weren’t invalidated.</li><li>The SwiftUI .id() modifier was doing more harm than good.</li></ul><p>It was death by a thousand cuts. My tools weren’t giving me what I needed in real time.</p><p>So I built one.</p><h4>🧪 Solution: A Custom Memory Profiler for Swift Apps</h4><p>I needed to observe memory usage during app lifecycle events — especially tab switches — without the latency of Instruments or Xcode debugging. So I created a <strong>real-time memory monitoring service</strong> using low-level system APIs.</p><h4>Here’s what I implemented:</h4><ul><li>Real-Time Monitoring<br>I used mach_task_basic_info to access the app’s <strong>resident memory size</strong> and paired it with ProcessInfo.processInfo.physicalMemory for context.</li><li>Automatic Threshold Alerts<br>By default, the profiler sets a warning threshold at <strong>70% of physical memory</strong> — a common best practice. It logs a warning if memory exceeds that.</li><li>Leak Pattern Detection<br>It is structured to track <strong>peak memory usage</strong>, <strong>record historical data</strong>, and prepare for advanced analysis.</li><li>Timer-Driven Sampling<br>Every 60 seconds, the profiler captures current stats and logs trends — lightweight enough for debug builds and safe for Swift Packages.</li></ul><h4>🔍 Key App Fixes Beyond the Profiler</h4><p>The profiler helped me identify <strong>specific root causes</strong> in the UI:</p><ol><li><strong>View Recreation via </strong><strong>.id()</strong></li></ol><ul><li>SwiftUI’s .id modifier can force complete reinitialization. I was using it on tab switches, unintentionally keeping views alive.</li><li>Solution: Removed .id usage where not needed.</li></ul><pre>TabView(selection: $selectedTab) {<br>    HomeView()<br>        .id(UUID()) // 🔴 This forces recreation on every tab switch<br>        .tabItem { Text(&quot;Home&quot;) }<br>        .tag(0) // Tag is enough, no ID needed.<br><br>    SettingsView()<br>        .id(UUID()) // 🔴 Same issue here<br>        .tabItem { Text(&quot;Settings&quot;) }<br>        .tag(1)// Tag is enough, no ID needed.<br>}</pre><p>2. <strong>Asynchronous task lifecycle</strong></p><pre>final class MyViewModel: ObservableObject {<br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br>    private var task: Task&lt;Void, Never&gt;?<br>    private let apiClient: APIClientProtocol<br>  <br>    init(apiClient: APIClientProtocol) {<br>        self.apiClient = apiClient<br>    }<br>    func loadPosts() {<br>        // use task properly.<br>        task = Task { [weak self] in<br>            do {<br>                let posts: [PostDTO] = try await self?.apiClient.execute(.getPosts) ?? []<br>                // <br>            } catch {<br>                // <br>            }<br>        }<br>    }<br>}</pre><p>❌ Combine pipelines weren’t being torn down.</p><pre>final class PostsViewModel: ObservableObject {<br>    private let apiClient: APIClientProtocol<br>    private var loadTask: Task&lt;Void, Never&gt;?<br><br>    init(apiClient: APIClientProtocol) {<br>        self.apiClient = apiClient<br>    }<br><br>    deinit {<br>        loadTask?.cancel()<br>    }<br><br>    /// Loads posts asynchronously using the API client.<br>    /// - Note: Cancels any ongoing load operation before starting a new one. The task is cancelled on deinit.<br>    func loadPosts() {<br>        loadTask?.cancel()<br><br>        loadTask = Task { [weak self] in<br>            guard let self else { return }<br><br>            do {<br>                let posts: [PostDTO] = try await apiClient.execute(.getPosts)<br>                // Assign or process `posts` as needed<br>            } catch {<br>                // Handle error<br>            }<br>        }<br>    }<br>}</pre><p>✅ Manual task management: task handle stored and cancelled in deinit for proper lifecycle control.</p><p>3. <strong>Timer Leaks</strong></p><ul><li>Timers retained self.</li><li>Solution: Used [weak self] captures, and explicitly invalidate() timers on view disappear.</li></ul><pre>final class CountdownViewModel: ObservableObject {<br>    private var timer: Timer?<br>    @Published var secondsLeft: Int = 60<br><br>    func startTimer() {<br>        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in<br>            self.secondsLeft -= 1<br>        }<br>    }<br>}</pre><blockquote>❌ The problem? Timer strongly retained self, and since I didn’t invalidate it, the view model stayed in memory even after the view disappeared.</blockquote><pre>final class CountdownViewModel: ObservableObject {<br>    private var timer: Timer?<br>    @Published var secondsLeft: Int = 60<br><br>    func startTimer() {<br>        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in<br>            self?.secondsLeft -= 1<br>        }<br>    }<br><br>    deinit {<br>        timer?.invalidate()<br>    }<br>}</pre><blockquote>✅ The fix involved two parts: using [weak self] to avoid retain cycles, and explicitly invalidating the timer in deinit.</blockquote><h4>📈 The Results</h4><p>Once I integrated the profiler and resolved the root causes, the improvements were immediate and measurable:</p><ul><li><strong>Tab switching memory impact</strong> dropped from 10–15MB to just 1–2MB.</li><li><strong>Total memory usage after 10 minutes</strong> stabilized around 211MB, instead of ballooning past 310MB.</li><li><strong>Responsiveness issues</strong> completely disappeared — the app remained fluid even under stress.</li><li><strong>Leak patterns</strong>, previously triggered by multiple sources, were fully eliminated.</li></ul><p>These optimizations not only made the app more stable but also gave me a repeatable system for catching regressions before they escalate. The app now maintains <strong>stable memory usage</strong>, and the profiler gives me confidence every new build won’t regress.</p><h4>Why I Open-Sourced It</h4><p>I didn’t build this for fun (though it was fun). I built it because I needed visibility into a system-level issue that was otherwise invisible until too late. And I figured other iOS devs might be dealing with the same problem — unknowingly shipping apps with slow-growing leaks.</p><p>So I open-sourced it.</p><h4>You can find it here:</h4><p><a href="https://github.com/egzonpllana/MemoryProfiler">https://github.com/egzonpllana/MemoryProfiler</a></p><h4>🔧 Under the Hood</h4><p>Here’s a peek at what the service gives you out of the box:</p><pre>let profiler = MemoryProfilerService()<br>profiler.startMonitoring()<br>profiler.logMemoryUsage(context: &quot;TabSwitch&quot;)</pre><p>You can check memory stats:</p><pre>let stats = profiler.getMemoryStats()<br>print(stats.usedMemory)</pre><p>Or set a custom warning threshold:</p><pre>profiler.setMemoryWarningThreshold(300 * 1024 * 1024) // 300MB</pre><p>And yes, it’s safe to use in Swift Packages, doesn’t require UIKit, and respects `DEBUG`-only environments out of the box.</p><h4>Final Thoughts</h4><p>Memory issues in SwiftUI aren’t always obvious — especially with its declarative magic. But they’re real. When you see gradual memory climbs during usage, don’t just blame Instruments for being slow — build tools that work for you.</p><p>This profiler helped me <strong>stabilize performance</strong>, <strong>eliminate leaks</strong>, and <strong>ship confidently</strong>.</p><p>Try it, fork it, improve it.<br>Let’s build apps that run lean — not leak.</p><p>Let me know what you think in the comments — and if you use this in your app, I’d love to hear your results.</p><p>📬 Follow me here and on <a href="https://github.com/egzonpllana">GitHub</a> for more dev tools and performance insights.</p><p>👨‍💻 Lets connect on LinkedIn: https://www.linkedin.com/in/egzon-pllana/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=282aef170df5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EventHorizon — A thread-safe networking layer in Swift with Sendable and async-await]]></title>
            <link>https://levelup.gitconnected.com/eventhorizon-a-thread-safe-networking-layer-in-swift-with-sendable-and-async-await-b2ef8cfe57ef?source=rss-73807a6a3e05------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2ef8cfe57ef</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Egzon Pllana]]></dc:creator>
            <pubDate>Wed, 09 Apr 2025 00:45:22 GMT</pubDate>
            <atom:updated>2025-04-09T00:45:22.532Z</atom:updated>
            <content:encoded><![CDATA[<h3>EventHorizon — A thread-safe networking layer in Swift with Sendable and async-await</h3><p><a href="https://github.com/egzonpllana/EventHorizon">EventHorizon</a> is a lightweight, thread-safe package designed to build a clean and organized network communication layer in Swift. It offers a type-safe and customizable approach to handling network requests with the latest Swift 6 features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sH9b4qNw5pyf5uYRql-8Rg.png" /></figure><blockquote>The name EventHorizon represents the package’s role as the ultimate control point for network requests. Just as an event horizon marks the boundary of a black hole, where nothing escapes its pull, this package captures, shapes, and directs network communication with precision. It ensures that every request and response passes through a structured and seamless pipeline, making network communication both reliable and efficient.</blockquote><h4>Elegant and type-safe API</h4><pre>let posts: [PostDTO] = try await apiClient.request(APIEndpoint.getPosts)</pre><h4>Features</h4><ul><li>Type-safe network requests using Swift’s generics.</li><li>Asynchronous execution with Swift’s async/await.</li><li>Multi-part request support with progress tracking.</li><li>Interceptor-based customization for request and response handling.</li><li>Direct access to URLSession for low-level operations, SSL pining, mocking, caching rules, unit testing, and more.</li></ul><h4>Interceptors</h4><p>EventHorizon includes a set of built-in interceptors, but you can create and inject your custom interceptors as needed.</p><ul><li>AuthInterceptor - Injects an authorization token into network requests.</li><li>LoggingInterceptor - Logs request and response details for debugging.</li><li>RequestTimeoutInterceptor - Configures custom timeout intervals for requests.</li><li>HeaderInjectorInterceptor - Adds custom headers to outgoing requests.</li><li>RetryInterceptor - Automatically retries failed requests based on status codes.</li></ul><h3>Networking Layer — Data Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RMTC0fRSlAAlqv55WRaZg.png" /></figure><h4>API Layer components:</h4><ul><li>APIEndpoint: Defines API routes and configurations.</li><li>APIClient: Manages network requests and responses.</li><li>Network Interceptor: Handles request modifications (e.g., authentication, logging).</li><li>Role: This layer abstracts networking details, ensuring maintainability and separation of concerns.</li><li>Flow: The repository calls APIEndpoint → passes it to APIClient → processed through Network Interceptor before sending the request.</li></ul><h4>URLSession</h4><ul><li>Role: The final networking component that executes HTTP requests and retrieves responses.</li><li>Flow: APIClient sends the request via URLSession, receives the response, and decodes it using JSONDecoder.</li></ul><h4>Data Flow</h4><ol><li>Repository interacts with APIEndpoint and APIClient.</li><li>Network Interceptor modifies the request (if needed) before reaching URLSession.</li><li>URLSession fetches data from the remote server.</li><li>Response data is decoded and propagated back through the layers.</li></ol><h4>Example</h4><p>Create an APIClient instance with interceptors:</p><pre>import EventHorizon<br><br>let apiClient = APIClient(<br>    interceptors: [ // Inject any NetworkInterceptor<br>        LoggingInterceptor()<br>    ]<br>)<br><br>// Request with expected response<br>let posts: [PostDTO] = try await apiClient.request(APIEndpoint.getPosts)<br><br>// Request Void<br>try await apiClient.request(APIEndpoint.createPost(newPost))<br><br>// Multi-part request with tracking progress<br>try await apiClient.request(<br>    APIEndpoint.uploadImage(...),<br>    progressDelegate: UploadProgressDelegateProtocol<br>)</pre><h4>Unit Testing with MockAPIClient</h4><p>You can use MockAPIClient to mock network requests while unit testing your ViewModel.</p><pre>import XCTest<br>@testable import EventHorizon<br><br>final class MyViewModelTests: XCTestCase {<br><br>    var mockAPIClient: MockAPIClient!<br>    var viewModel: MyViewModel!<br><br>    override func setUp() async throws {<br>        mockAPIClient = MockAPIClient()<br>        viewModel = MyViewModel(apiClient: mockAPIClient)<br>    }<br><br>    func testFetchData_Success() async throws {<br>        let mockResponse = MockResponse(message: &quot;Success&quot;, status: &quot;OK&quot;)<br>        try mockAPIClient.setMockResponse(mockResponse, forPath: &quot;/mock&quot;)<br>        <br>        try await viewModel.fetchData()<br>        <br>        XCTAssertEqual(viewModel.message, &quot;Success&quot;)<br>    }<br><br>    func testFetchData_Failure() async throws {<br>        mockAPIClient.setShouldThrowError(true)<br>        <br>        do {<br>            try await viewModel.fetchData()<br>            XCTFail(&quot;Expected error but got success.&quot;)<br>        } catch {<br>            XCTAssertNotNil(error)<br>        }<br>    }<br>}</pre><h4>Mocking URL Session</h4><p>You can use a custom URL Session and Interceptors to inject into the APIClient.</p><pre>let apiClient = APIClient(<br>    session: NetworkSessionProtocol, // Inject any NetworkSessionProtocol.<br>    interceptors: [any NetworkInterceptor] // Inject any Mocked Interceptor.<br>)</pre><h4>EventHorizon package:</h4><p><a href="https://github.com/egzonpllana/EventHorizon">https://github.com/egzonpllana/EventHorizon</a></p><h4>Real app example:</h4><p><a href="https://github.com/egzonpllana/NetworkLayerSwift6">https://github.com/egzonpllana/NetworkLayerSwift6</a></p><h4>The meaning behind this package name: EventHorizon</h4><p><a href="https://www.space.com/black-holes-event-horizon-explained.html">https://www.space.com/black-holes-event-horizon-explained.html</a></p><h4>Let’s Connect</h4><ul><li>LinkedIn: <br><a href="https://www.linkedin.com/in/egzon-pllana">https://www.linkedin.com/in/egzon-pllana</a></li><li>GitHub: <br><a href="https://github.com/egzonpllana">https://github.com/egzonpllana</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2ef8cfe57ef" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/eventhorizon-a-thread-safe-networking-layer-in-swift-with-sendable-and-async-await-b2ef8cfe57ef">EventHorizon — A thread-safe networking layer in Swift with Sendable and async-await</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The important difference between RunLoop.main and DispatchQueue.main]]></title>
            <link>https://medium.com/@egzonpllana/the-important-difference-between-runloop-main-and-dispatchqueue-main-83d5dd3ca972?source=rss-73807a6a3e05------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d5dd3ca972</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[publishers]]></category>
            <dc:creator><![CDATA[Egzon Pllana]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 11:27:56 GMT</pubDate>
            <atom:updated>2024-10-09T11:27:56.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*86ghSI0848u_ykeeaT827A.png" /><figcaption>Apple.com Combine Events Handler Documentation</figcaption></figure><p>This article comes after so many hours debugging why a Combine publisher is causing UI animations to stop/pause when I scroll other the content, mostly in SwiftUI views?…. The answer is pretty simple, you decide how to receive Combine published values, more exactly in which scheduler/thread.</p><p>Consider you will have a property in one of your services or view models like this:</p><pre>// Encapsulate publisher subject<br>private let stopwatchLapTimeSubject = PassthroughSubject&lt;Double, Never&gt;()<br><br>// Publisher property, other can observe from here.<br>var stopwatchLapTimePublisher: AnyPublisher&lt;Double, Never&gt; {<br>    stopwatchLapTimeSubject.eraseToAnyPublisher()<br>}<br><br>// Publish/send new values to the publisher<br>stopwatchLapTimeSubject.send(28.50)</pre><p>You can subscribe to this publisher like this from any SwiftUI view:</p><pre>.onAppear {<br>    viewModel.stopwatchLapTimePublisher<br>        .subscribe(on: DispatchQueue.global(qos: .background))<br>        .receive(on: RunLoop.main) // &lt;---- vs `DispatchQueue.main`<br>        .sink { newLapTime in<br>            print(&quot;New lap time received: \(newLapTime)&quot;)<br>        }<br>        .store(in: &amp;cancellables)<br>}</pre><p>One important parameter here is on which scheduler you want to receive updates from this publisher? You have these options:</p><ul><li><strong>RunLoop</strong></li><li><strong>DispatchQueue</strong></li><li><strong>OperationQueue</strong></li><li><strong>ImmediateScheduler</strong></li></ul><p>Let’s compare two most importants, <strong>RunLoop</strong> and <strong>DispatchQueue</strong> . The difference between .receive(on: RunLoop.main) and .receive(on: DispatchQueue.main) can impact how and when the Combine pipeline handles value delivery, especially during<strong> UI interactions</strong>. Let’s explore why this difference matters and how it can affect your Combine-based applications:</p><h4>RunLoop.main</h4><ul><li>Operates based on the main run loop of the current thread.</li><li>Runs in specific modes such as default, common, or tracking.</li><li>During certain UI activities (e.g., scrolling), the main run loop switches modes (e.g., to UITrackingRunLoopMode), which can pause or delay tasks scheduled on the run loop if they are in a different mode.</li><li>This behavior can cause Combine pipelines to temporarily stop receiving values when intensive UI events are happening.</li></ul><h4>DispatchQueue.main</h4><ul><li>Schedules work directly on the main thread using GCD (Grand Central Dispatch).</li><li>It does not depend on run loop modes and does not pause during UI events like scrolling or drag gestures.</li><li>Consistently delivers values on the main thread, regardless of run loop state, making it a more reliable choice for UI updates.</li></ul><h4>🤔 Why does this difference matter?</h4><p>When you use .receive(on: RunLoop.main), Combine schedules downstream subscribers to receive values based on the main run loop’s current mode. If the UI is performing actions like scrolling, the run loop can switch modes, and if your Combine pipeline is using a mode like RunLoop.Mode.default, values might not be delivered until the run loop returns to that mode.</p><p>With .receive(on: DispatchQueue.main), the values are delivered directly on the main thread, unaffected by these run loop mode changes. This ensures that the pipeline operates predictably, even during interactions like scrolling or other high-priority UI events.</p><h4>When to use each?</h4><p><strong>RunLoop.main: </strong>Use this if your pipeline is lightweight and you want it to align with run loop activities. It might be useful when coordinating with other run loop-based tasks. <strong>Be aware</strong> that this can cause missed or delayed events if the run loop switches modes (e.g., during gestures).</p><p><strong>DispatchQueue.main: </strong>This is the preferred choice when updating UI elements because it schedules tasks directly on the main thread and is not sensitive to run loop mode changes. It <strong>ensures</strong> smooth value delivery regardless of run loop states, which is critical for UI-bound operations.</p><h4>Example to illustrate the issue</h4><p>Let’s say you have a Combine pipeline that updates a label’s text based on some background operation, and you use .receive(on: RunLoop.main). If the user starts scrolling a UIScrollView, you might notice that updates to the label <strong>pause</strong> or are <strong>missed</strong> during the scroll. This is because the run loop is temporarily in UITrackingRunLoopMode and not RunLoop.Mode.default, so values aren’t delivered as expected.</p><p>Switching to .receive(on: DispatchQueue.main) resolves this issue because the values are delivered on the main thread, independent of the run loop mode.</p><h4>🤷 How to choose?</h4><ul><li>Use .receive(on: DispatchQueue.main) for consistent UI updates or any Combine pipeline that interacts with UIKit components.</li><li>Use .receive(on: RunLoop.main) only if you specifically want to schedule based on run loop activities or when working with legacy run loop-based systems.</li></ul><h4>Summary</h4><ul><li>RunLoop.main<strong>:</strong> Depends on the run loop’s current mode. Can cause delivery delays during certain UI interactions.</li><li>DispatchQueue.main<strong>:</strong> Directly schedules on the main thread. Consistent and reliable for UI updates.</li></ul><h4>⛳️ One last thing before you go: The importance of<strong> .subscribe(on:)</strong></h4><pre>.onAppear {<br>    viewModel.stopwatchLapTimePublisher<br>        .subscribe(on: DispatchQueue.global(qos: .background)) // &lt;----<br>        .receive(on: DispatchQueue.main)<br>        .sink { newLapTime in<br>            print(&quot;New lap time received: \(newLapTime)&quot;)<br>        }<br>        .store(in: &amp;cancellables)<br>}</pre><ul><li>The .subscribe(on:) operator specifies the dispatch queue on which the subscription side-effects and upstream operations are performed.</li><li>When you use .subscribe(on:) with DispatchQueue.global(qos: .background), you ensure that <strong>the initial work of subscribing</strong> to the publisher and <strong>any upstream processing</strong> (like network requests or heavy computations) are performed on a <strong>background thread</strong>.</li></ul><p><strong>Why is </strong><strong>.subscribe(on:) beneficial?</strong></p><ul><li>If your stopwatchLapTimePublisher has any <strong>heavy computations</strong> or <strong>non-UI related side-effects</strong> when it is subscribed to (e.g., reading from a database, file operations, or long-running calculations), using .subscribe(on:) ensures these operations are offloaded to a background thread. This prevents blocking the <strong>main thread</strong>, which could otherwise cause your UI to freeze or become unresponsive.</li></ul><p><strong>When to use </strong><strong>.subscribe(on:) vs </strong><strong>.receive(on:)?</strong></p><ul><li>.subscribe(on:) is used to control the thread where <strong>subscription and upstream operations</strong> take place.</li><li>.receive(on:) is used to control the thread where <strong>downstream operations</strong> (e.g., handling the emitted values, updating the UI) occur.</li></ul><h4>Example Scenario</h4><p>If stopwatchLapTimePublisher performs a complex calculation or interacts with a data source (e.g., reading from a file or querying a database) during its subscription phase, you want to offload that work to a background queue using .subscribe(on:). After this heavy lifting is done, you can use .receive(on:) to switch back to the main queue, ensuring that the UI updates are performed on the main thread, which is a requirement for UIKit or SwiftUI.</p><p>Thank you for following along! I encourage you to share any feedback or suggestions you may have about Combine framework and its usage in Swift development.</p><h4>Resources</h4><p><strong>Receiving and Handling Events with Combine</strong><br>(<a href="https://developer.apple.com/documentation/combine/receiving-and-handling-events-with-combine">https://developer.apple.com/documentation/combine/receiving-and-handling-events-with-combine</a>)</p><p><strong>receive(on:options:)</strong><a href="https://developer.apple.com/documentation/combine/publisher/receive(on:options:)"><br>https://developer.apple.com/documentation/combine/publisher/receive(on:options:)</a></p><h4>Let’s Connect</h4><ul><li><strong>LinkedIn</strong>: <br><a href="https://www.linkedin.com/in/egzon-pllana">https://www.linkedin.com/in/egzon-pllana</a></li><li><strong>GitHub</strong>: <br><a href="https://github.com/egzonpllana">https://github.com/egzonpllana</a></li></ul><h4>Read more articles written by me</h4><p><a href="https://medium.com/@egzonpllana">https://medium.com/@egzonpllana</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d5dd3ca972" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Concurrency in Swift 6 with Sendable protocol, MainActor, and async-await]]></title>
            <link>https://medium.com/@egzonpllana/understanding-concurrency-in-swift-6-with-sendable-protocol-mainactor-and-async-await-5ccfdc0ca2b6?source=rss-73807a6a3e05------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ccfdc0ca2b6</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[async-await-in-swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[sendable]]></category>
            <dc:creator><![CDATA[Egzon Pllana]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 18:28:41 GMT</pubDate>
            <atom:updated>2025-05-14T08:43:02.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dot37ujRW3Wj6xW0zbQUaA.png" /><figcaption>Concurrency — Apple documentation.</figcaption></figure><blockquote>This is part of the article <a href="https://medium.com/p/927fa1d0cce8">Building a generic, thread-safe Networking Layer in Swift 6</a>.</blockquote><h3>Concurrency</h3><p>Concurrency is about performing multiple tasks at the same time. In programming, it means you can run different pieces of code simultaneously rather than one after the other. This is especially useful for tasks that can be done independently, like downloading files, processing data, or handling user inputs. In Swift, you manage concurrency using:</p><ul><li><strong>Grand Central Dispatch (GCD)</strong>: This is a low-level API for managing concurrent tasks and queues. It allows you to execute code asynchronously on different threads.</li><li><strong>Operation Queues</strong>: Built on top of GCD, Operation Queues provide a higher-level abstraction for managing concurrent operations. You can use Operation and OperationQueue to handle dependencies, priorities, and cancellation of tasks.</li><li><strong>Swift Concurrency (</strong><strong>async/</strong><strong>await </strong>and<strong> Tasks)</strong>: Introduced in Swift 5.5, this is a more modern and user-friendly approach to managing asynchronous code. It uses async and await keywords to write asynchronous code that looks synchronous. You can also use structured concurrency with Task and TaskGroup.</li><li><strong>Combine Framework</strong>: While not strictly a concurrency mechanism, Combine allows you to work with asynchronous data streams and apply operators to handle events over time. It’s useful for combining, transforming, and reacting to asynchronous events.</li><li><strong>Actors</strong>: Swift’s actor model, introduced with Swift Concurrency, helps manage state in a thread-safe way, allowing you to isolate data and prevent race conditions.</li></ul><h4>Thread Safety</h4><p>Thread safety ensures that your code works correctly when multiple threads access the same data at the same time. If your code is not thread-safe, you might run into problems like:</p><ul><li><strong>Data races</strong>: When two or more threads try to read and write the same data simultaneously, leading to unpredictable results.</li><li><strong>Crashes</strong>: When data is accessed in an unexpected state due to concurrent modifications.</li></ul><h3>What is async-await?</h3><p>In Swift, async-await is part of Swift&#39;s structured concurrency model, introduced in Swift 5.5, designed to simplify and improve how asynchronous operations are handled.</p><p>Before Swift introduced structured concurrency, asynchronous programming in Swift relied heavily on completion handlers or third-party frameworks like Combine or RxSwift. These approaches, while powerful, made code harder to reason about, harder to maintain, and prone to callback hell, deeply nested closures, and potential race conditions.</p><p>async-await provides a modern, more readable, and structured way of working with asynchronous code. Instead of chaining callbacks, you write code that looks and behaves like synchronous code but without blocking the thread.</p><h4><strong>async</strong> Functions</h4><p>An async function is one that performs some asynchronous work. It must be marked with the async keyword, signaling that it suspends execution at certain points while waiting for results. When a function is async, you must call it from within an await context.</p><pre>func fetchData() async throws -&gt; Data {<br>    // Perform async task here<br>}</pre><h4><strong>await</strong> Keyword</h4><p>To call an async function, you must use await. This tells Swift that the function will &quot;pause&quot; until the asynchronous operation completes, but it doesn&#39;t block the current thread. The result is much more readable code.</p><pre>Task {<br>  do {<br>    let data = try await fetchData()<br>  } catch {<br>    print(error)<br>  }<br>}</pre><h4><strong>async let</strong></h4><p>Use async let to concurrently initialize multiple async values in a single scope.</p><pre>func fetchData() async -&gt; (String, Int) {<br>    async let stringData = fetchString()<br>    async let intData = fetchInt()<br>    <br>    return await (stringData, intData)<br>}</pre><h4><strong>When should you use </strong><strong>async and </strong><strong>await?</strong></h4><ul><li><strong>Non-blocking I/O</strong>: When you are performing network requests, disk reads/writes, or any task where waiting for a response could otherwise freeze the UI or delay other operations.</li><li><strong>Concurrency Control</strong>: When you need to perform multiple tasks concurrently without running them in separate threads manually. This helps in simplifying error handling and state management.</li></ul><h3>MainActor — What it is and when to use it</h3><ul><li>The code in the methods interacts directly with the UI (e.g., updating UI elements like lists, labels, or progress bars).</li><li>The protocol or its methods are designed to be run on the main thread for thread safety, especially if you deal with UI updates or other main-thread-sensitive operations (such as updating <a href="http://twitter.com/Published">@Published</a> properties in ObservableObject).</li></ul><p>Additionally, If most of the properties and methods in your view model involve UI updates, keeping <a href="http://twitter.com/MainActor">@MainActor</a> at the protocol level simplifies the code.</p><pre>@MainActor<br>protocol HomeViewModelProtocol: ObservableObject { ... }</pre><p>However, if you’re doing a lot of background work (e.g., networking or data processing) and only occasionally need to update the UI, I’d recommend selective use of <a href="http://twitter.com/MainActor">@MainActor</a> on the properties and methods that actually need it. This way, you get the best of both worlds: concurrency where possible and main thread safety for UI updates.</p><h4>Reasons to use <a href="http://twitter.com/MainActor">@MainActor</a></h4><p>@MainActor in Swift is a concurrency attribute that indicates that a particular method, function, or property should always be executed on the main actor. This is particularly useful when you want to ensure that UI-related tasks or tasks that must run on the main thread are safely and consistently executed on the correct thread.</p><ul><li>UI updates (because UI operations must happen on the main thread).</li><li>Ensuring thread safety when dealing with shared mutable state.</li><li>Handling Swift concurrency with actors in a way that ensures certain code runs on the main thread.</li></ul><h3>Sendable Protocol</h3><p>Since Swift 6 emphasizes safe concurrency, ensuring that types conform to Sendable helps guarantee that data passed across concurrency boundaries is safely shared.</p><h4>Sendable Conformance</h4><p>For a class to conform to Sendable, it must guarantee that its state is safely shared across threads, meaning:</p><ul><li>Its properties must either be Sendable themselves or designed so that there is no race condition when accessed concurrently.</li><li>In some cases, using <a href="http://twitter.com/unchecked">@unchecked</a> Sendable is necessary if you’re sure the class is safe but the compiler can’t guarantee it due to the class’s design (e.g., mutable state protected by locks), so this responsibility is <strong>in the hands</strong> of the developer and not to the compiler checks.</li></ul><p>In Swift, certain types are automatically considered Sendable and don&#39;t require you to manually conform them to the Sendable protocol. This is because they are inherently safe to use across threads due to their immutability or specific guarantees.</p><pre>// A class that is not Sendable because it contains mutable state<br>class Counter {<br>    var count: Int = 0<br>    <br>    func increment() {<br>        count += 1<br>    }<br>}<br><br>// An actor that handles mutable state safely<br>actor CounterActor {<br>    private var count: Int = 0<br><br>    func increment() {<br>        count += 1<br>    }<br>}</pre><p>CounterActor is an actor that safely manages its mutable state. The Swift runtime ensures that access to the countproperty is serialized, preventing data races.</p><h4>@unchecked Sendable</h4><p><a href="http://twitter.com/unchecked">@unchecked</a> Sendable is used when you want to tell the Swift compiler that a class or type is safe to be sent across threads, even if the compiler can&#39;t verify that it&#39;s actually safe. This attribute is necessary when the type doesn&#39;t automatically conform to Sendable but you&#39;re confident that your implementation is thread-safe. Example of a class that uses synchronization to ensure thread safety:</p><pre>final class MyClass: @unchecked Sendable {<br>    private var value: Int = 0<br>    private let queue = DispatchQueue(label: &quot;com.myapp.syncQueue&quot;)<br><br>    func updateValue(_ newValue: Int) {<br>        queue.sync {<br>            self.value = newValue<br>        }<br>    }<br>    <br>    func getValue() -&gt; Int {<br>        return queue.sync { value }<br>    }<br>}</pre><h4><strong>Why @unchecked Sendable?</strong></h4><p>By default, the compiler performs strict checks to ensure that types marked as Sendable can safely be transferred across threads. These checks ensure that:</p><ul><li>Mutable state isn’t accidentally shared between threads without proper synchronization.</li><li>All properties of the type conform to Sendable.</li></ul><h4>@preconcurrency attribute</h4><p><a href="http://twitter.com/preconcurrency">@preconcurrency</a> is an attribute in Swift used to mark a type, function, or declaration as being from a pre-concurrency codebase, which means it was written before Swift&#39;s concurrency model (introduced in Swift 5.5) was available. This attribute helps the Swift compiler to relax some of its stricter concurrency checks for backward compatibility.</p><pre>@preconcurrency<br>class LegacyClass {<br>    var data: SomeType<br>    init(data: SomeType) {<br>        self.data = data<br>    }<br>}</pre><p>When you use @preconcurrency, you&#39;re essentially telling the compiler that the code or API you&#39;re working with might not conform to Swift&#39;s new concurrency rules but that it&#39;s still safe to use in a concurrent context.</p><h4>Common use cases for<strong> </strong><strong>@preconcurrency</strong></h4><ol><li><strong>Legacy Code Interoperability</strong>: If you’re working with code (especially from third-party libraries) that was written before Swift’s concurrency model, you can use @preconcurrency to prevent the compiler from enforcing strict concurrency checks that didn&#39;t exist when the code was originally written.</li><li><strong>Class and Protocol Conformance</strong>: You might apply @preconcurrency when you need to conform to a protocol or work with a class that hasn&#39;t been updated for concurrency but is being used in a concurrent environment.</li><li><strong>Imported C and Objective-C APIs</strong>: When importing APIs from C or Objective-C that predate Swift’s concurrency, you might mark their types or methods as @preconcurrency to allow their use without having to retrofit them for Sendable conformance or actor isolation.</li></ol><p><strong>Important Considerations</strong></p><ul><li><strong>Backward Compatibility</strong>: @preconcurrency is mainly useful when you&#39;re transitioning code to Swift’s concurrency model but still have to interact with legacy code that doesn’t adhere to the new concurrency guarantees.</li><li><strong>Compiler Relaxation</strong>: It doesn’t make your code thread-safe; it simply relaxes some of the stricter concurrency rules enforced by the compiler. You need to be cautious when using it, as it may lead to potential concurrency issues if the code isn’t properly designed for concurrent execution.</li></ul><h3>Summary</h3><ul><li>Use <a href="http://twitter.com/MainActor">@MainActor</a> to ensure that a function, property, or type runs on the main thread, which is required for updating UI elements. It helps guarantee thread safety when interacting with the user interface in Swift’s concurrency model. thread management for UI updates was often done using DispatchQueue.main.async to ensure UI work was performed on the main thread.</li><li>async allows a function to perform work asynchronously, while await is used to wait for the end of the function’s execution until the asynchronous operation completes, but rather than pausing, it enables the function to yield control back to the calling context, allowing other work to continue during the suspension, ensuring non-blocking concurrency. In <em>older</em> Swift, asynchronous operations were commonly handled using completion handlers or escaping closures .</li><li>Use Task { … } to create a new concurrent task in Swift. It’s often used for running asynchronous code from synchronous contexts, allowing you to perform async work on a background thread without blocking the main thread. Previously, you might have used DispatchQueue.global().async or OperationQueue to run work concurrently on background threads</li><li>Conforming to Sendable protocol, Swift automatically enforces thread-safety rules for types, ensuring that instances passed between concurrent tasks won’t cause data races. Previously, ensuring thread safety required careful manual checks to avoid data races, especially when sharing mutable state across threads.</li></ul><pre>// MARK: - Sendable Example<br>struct UserData: Sendable {<br>    let name: String<br>    let age: Int<br>}<br><br>// MARK: - MainActor Example<br>@MainActor<br>class UserViewModel {<br>    var userName: String = &quot;Guest&quot;<br><br>    func updateUserName(_ newName: String) {<br>        userName = newName<br>        print(&quot;User name updated on main thread to: \(userName)&quot;)<br>    }<br>}<br><br>// MARK: - Async-Await and Task Example<br>func fetchUserData() async -&gt; UserData {<br>    // Simulate a network delay<br>    try? await Task.sleep(nanoseconds: 1_000_000_000)<br>    return UserData(name: &quot;Alice&quot;, age: 30)<br>}<br><br>@MainActor<br>func updateUI() async {<br>    let userViewModel = UserViewModel()<br><br>    // Run async task to fetch user data in a background task<br>    Task {<br>        let userData = await fetchUserData()<br><br>        // After fetching, update UI on main thread<br>        await userViewModel.updateUserName(userData.name)<br>    }<br>}<br><br>// Call updateUI to start the process<br>Task {<br>    await updateUI()<br>}</pre><h4>👆 Explanation</h4><p>1. <strong>Sendable</strong>: UserData is marked as Sendable to ensure it can be safely transferred across concurrency domains without causing data races.</p><p>2. <strong>@MainActor</strong>: The UserViewModel class is annotated with @MainActor, ensuring any operations on its properties, such as updateUserName, are safely executed on the main thread.</p><p>3. <strong>async/await</strong>: fetchUserData() is an async function simulating a delay before returning some user data, think that we made a network call and waiting for the server response.</p><p>4. <strong>Task { … }</strong>: Inside the updateUI(), we use a Task { … } to run the fetchUserData function on a background thread. Once the data is fetched, it updates the UI on the main thread using await to switch context back to the main actor.</p><h3>Extra mile? 🏃‍♂️ Let’s go! 🚀</h3><p>In addition to <strong>@MainActor</strong>, <strong>async/await</strong>, <strong>Task { … }</strong>, and <strong>Sendable</strong>, which provide a robust foundation for modern concurrency in Swift, here are a few more concepts and tools from Swift 5.5 and Swift 6 that enhance concurrency and ensure safety:</p><h4><strong>TaskGroup</strong></h4><p>TaskGroup allows you to create a group of tasks and wait for them all to complete. It’s useful for managing multiple concurrent tasks and handling their results. <strong>The old approach</strong> was to use DispatchGroup to manage a group of concurrent tasks.</p><pre>func fetchMultipleUsers() async -&gt; [UserData] {<br>    await withTaskGroup(of: UserData.self) { group in<br>        let userIDs = [1, 2, 3]<br>        var results: [UserData] = []<br><br>        for id in userIDs {<br>            group.addTask {<br>                // Simulate fetching user data<br>                try? await Task.sleep(nanoseconds: 500_000_000)<br>                return UserData(name: &quot;User \(id)&quot;, age: id)<br>            }<br>        }<br><br>        for await user in group {<br>            results.append(user)<br>        }<br><br>        return results<br>    }<br>}</pre><h4><strong>Task Cancellation</strong></h4><p>Tasks can be canceled using the Task API, allowing you to handle task cancellation and cleanup gracefully. <strong>The old approach</strong> was to use flags like var isCancelled = false or custom cancellation mechanisms within asynchronous tasks to handle cancellations.</p><pre>func fetchUserData() async {<br>    let task = Task {<br>        // Simulate a long-running task<br>        try? await Task.sleep(nanoseconds: 5_000_000_000)<br>        print(&quot;Data fetched&quot;)<br>    }<br><br>    // Cancel the task<br>    task.cancel()<br>    do {<br>        try await task.value<br>    } catch {<br>        print(&quot;Task was cancelled&quot;)<br>    }<br>}</pre><h4><strong>Task Priorities</strong></h4><p>Tasks can be assigned priorities to influence their execution order.</p><pre>func highPriorityTask() {<br>    Task(priority: .high) {<br>        // Perform high-priority work<br>    }<br>}</pre><h4>Task.detached</h4><p>Creates a task that runs concurrently with its parent task and is not bound by the parent’s actor or task context. Useful for background work that doesn’t need the same context as the parent task.</p><pre>func backgroundTask() {<br>    Task.detached {<br>        // Perform background work independently<br>        print(&quot;Running in detached task&quot;)<br>    }<br>}</pre><h4><strong>Continuation API</strong></h4><p>Bridges between asynchronous and synchronous code. Useful for integrating with APIs that don’t yet support async/await.</p><pre>func fetchData() async -&gt; String {<br>    await withCheckedContinuation { continuation in<br>        // Simulate an async operation<br>        DispatchQueue.global().asyncAfter(deadline: .now() + 1) {<br>            continuation.resume(returning: &quot;Data fetched&quot;)<br>        }<br>    }<br>}</pre><h4><strong>@Sendable Closure Types</strong></h4><p>Closures marked as @Sendable ensure that they can be safely sent across concurrency domains. This is crucial for ensuring that closures do not capture non-sendable values inadvertently.</p><pre>func performTask(with completion: @Sendable @escaping () -&gt; Void) {<br>    Task {<br>        completion()<br>    }<br>}</pre><h4><strong>AsyncStream</strong></h4><p>Allows you to create an asynchronous stream of values, useful for scenarios where you need to provide a continuous stream of data.</p><pre>func numberStream() -&gt; AsyncStream&lt;Int&gt; {<br>    AsyncStream { continuation in<br>        var current = 1<br>        Task {<br>            while true {<br>                continuation.yield(current)<br>                current += 1<br>                try? await Task.sleep(nanoseconds: 1_000_000_000)<br>            }<br>        }<br>    }<br>}<br><br>func consumeNumbers() async {<br>    for await number in numberStream() {<br>        print(number)<br>    }<br>}</pre><h4>actors</h4><p>Actors are a new type in Swift designed to manage mutable state in a concurrent environment. They ensure that their data is accessed in a thread-safe manner. <strong>The old approach</strong> was to use DispatchQueue or OperationQueue for managing thread safety and coordinating access to shared state, for example in a class. Now instead of having a class, we can have the actor.</p><pre>actor UserManager {<br>    private var userData: UserData = UserData(name: &quot;Guest&quot;, age: 0)</pre><pre>    func updateUser(name: String, age: Int) {<br>        userData = UserData(name: name, age: age)<br>    }</pre><pre>    func getUser() -&gt; UserData {<br>        return userData<br>    }<br>}</pre><h4><strong>actor isolation and cross-actor references</strong></h4><p>You can access and manage state within an actor but need to handle references to actors carefully to avoid data races and ensure safe interaction.</p><pre>actor DataManager {<br>    private var data = [String]()<br>    <br>    func addData(_ item: String) {<br>        data.append(item)<br>    }<br>    <br>    func getData() -&gt; [String] {<br>        return data<br>    }<br>}<br><br>actor Processor {<br>    let manager = DataManager()<br>    <br>    func process() async {<br>        await manager.addData(&quot;Sample Data&quot;)<br>        let data = await manager.getData()<br>        print(data)<br>    }<br>}</pre><h4><strong>Actor-isolated Properties:</strong></h4><p>Properties inside an actor are automatically isolated to the actor’s context, ensuring thread-safe access.</p><pre>actor Counter {<br>    private(set) var value: Int = 0<br>    <br>    func increment() {<br>        value += 1<br>    }<br>    <br>    func getValue() -&gt; Int {<br>        return value<br>    }<br>}</pre><h3>Resources</h3><p><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/">Concurrency</a> <em>by Apple</em></p><h3>Let’s Connect</h3><ul><li>LinkedIn: <br><a href="https://www.linkedin.com/in/egzon-pllana">https://www.linkedin.com/in/egzon-pllana</a></li><li>GitHub: <br><a href="https://github.com/egzonpllana">https://github.com/egzonpllana</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ccfdc0ca2b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a generic, thread-safe Networking Layer in Swift 6]]></title>
            <link>https://medium.com/@egzonpllana/building-a-generic-thread-safe-networking-layer-in-swift-6-927fa1d0cce8?source=rss-73807a6a3e05------2</link>
            <guid isPermaLink="false">https://medium.com/p/927fa1d0cce8</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[sendable]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Egzon Pllana]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 09:17:49 GMT</pubDate>
            <atom:updated>2025-03-19T00:14:06.528Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a generic, thread-safe Networking Layer in Swift 6 with Interceptors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DX6dURqvLcaGjR25aWFfUQ.png" /><figcaption>Networking Layer in Swift 6 with Interceptors— Diagram</figcaption></figure><p>In this article, we will be using <a href="https://github.com/egzonpllana/EventHorizon"><strong>EventHorizon</strong></a><strong> Swift Package, </strong>a networking architecture that meets the thread safety requirements introduced in <strong>Swift 6</strong>, using Swift features such as async-await, Sendable, MainActor, etc. While many of these features appeared in Swift 5.5, they are becoming more important, especially in Swift 6. It also supports <strong>unit coverage</strong> up to 100%, I have already built unit tests in the example app that cover 70–80% of it. Find the example app GitHub link at the bottom of this article.</p><h3>Let&#39;s begin</h3><p>To make sure your project aligns with these changes, select project Target, go to Build Settings tab &gt; under “All &amp; Combined,” search for “Swift 6” or find the “Swift Compiler — Upcoming Features” section and enable these settings as you want and XCode will throw errors or warnings.</p><blockquote>There will be no future in Swift development without async await and Sendable protocol.</blockquote><p>The networking layer we will build will use the latest Swift concurrency APIs and thread-safe methods to avoid multi-threading issues or crashes. The key components of this networking layer will be the APIEndpoint protocol and the APIClient protocol. This will let us seamlessly execute network calls and obtain results with just one line of code⚡️.</p><pre>// Examples of using the Networking Layer<br><br>// GET Posts request<br>let posts: [PostDTO] = try await apiClient.request(APIEndpoint.getPosts)<br><br>// POST a post request<br>try await apiClient.requestVoid(APIEndpoint.createPost(newPost))<br><br>// Multi-part request<br>try await apiClient.requestWithProgress(APIEndpoint.uploadImage(...),<br>          progressDelegate: UploadProgressDelegateProtocol)</pre><h4>APIEndpointProtocol (<a href="https://github.com/egzonpllana/NetworkLayerSwift6/blob/main/NetworkingLayerSwift6/Architecture/Infrastructure/Networking/APIEndpoints.swift">GitHub</a>)</h4><p>APIEndpointProtocol defines the essential components of an API endpoint, such as HTTP methods, paths, base URLs, headers, URL parameters, and request body. It ensures a consistent and clear approach to constructing network requests through its urlRequest property, which assembles a URLRequest by combining these elements.</p><pre>protocol APIEndpointProtocol {<br>    /// HTTP method used by the endpoint.<br>    var method: HTTPMethod { get }<br>    <br>    /// Path for the endpoint.<br>    var path: String { get }<br>    <br>    /// Base URL for the API.<br>    var baseURL: String { get }<br>    <br>    /// Headers for the request.<br>    var headers: [String: String] { get }<br>    <br>    /// URL parameters for the request.<br>    var urlParams: [String: any CustomStringConvertible] { get }<br>    <br>    /// Body data for the request.<br>    var body: Data? { get }<br>    <br>    /// URLRequest representation of the endpoint.<br>    var urlRequest: URLRequest? { get }<br>    <br>    /// API version used by the endpoint.<br>    var apiVersion: APIVersion { get }<br>}<br><br>/// Endpoints<br>enum APIEndpoint: APIEndpointProtocol {<br>    case getPosts<br>    case createPost(PostDTO)<br>    case uploadImage(data: Data, fileName: String, mimeType: ImageMimeType)<br><br>    // Define all properties required by the protocol,<br>    // matching your backend API.<br>}</pre><h4>APIClientProtocol (<a href="https://github.com/egzonpllana/NetworkLayerSwift6/blob/main/NetworkingLayerSwift6/Architecture/Infrastructure/Networking/APIClient.swift">GitHub</a>)</h4><p>APIClientProtocol defines the contract for making network requests and handling responses in a structured way. It abstracts away the complexity of sending HTTP requests and decoding responses, allowing you to focus on the data and logic. The protocol supports asynchronous operations and is designed to work with any type that conforms to Codable &amp; Sendable Protocols.</p><p><strong>Key methods include:</strong></p><ul><li>request(_:decoder:) Sends a request using URLSession, decodes the response into a specified type, and returns the result.</li><li>requestVoid(_:) Sends a request that provides no response data, it can only throw an error.</li><li>requestWithAlamofire(_:decoder:) Sends a request using Alamofire and decodes the response.</li><li>requestWithProgress(_:progressDelegate:) Sends a request with raw data, and with an optional upload progress tracking.</li></ul><pre>func request&lt;T: Decodable &amp; Sendable&gt;(<br>    _ endpoint: any APIEndpointProtocol,<br>    decoder: JSONDecoder<br>) async throws -&gt; T {<br>    guard let request = endpoint.urlRequest else {<br>        throw APIClientError.invalidURL<br>    }<br>    <br>    // Perform the network request and decode the data<br>    let data = try await performRequest(request)<br>    do {<br>        return try decoder.decode(T.self, from: data)<br>    } catch {<br>        // Handle decoding errors<br>        throw APIClientError.decodingFailed(error)<br>    }<br>}</pre><p><strong>Parameters</strong></p><ul><li>endpoint This parameter represents the API endpoint that contains the URL request configuration. The any keyword allows for any type that conforms to APIEndpointProtocol. This protocol typically includes properties or methods to provide the URL request needed for the network call.</li><li>decoder This parameter is an instance of JSONDecoder, which converts JSON data into instances of types that conform to the Decodable protocol.</li></ul><p><strong>Generic Type T</strong></p><ul><li>T: Decodable &amp; Sendable is a generic type that must conform to both Decodable and Sendable protocols.</li><li>Decodable This protocol allows the type to be initialized from JSON data. It ensures that the type can be created from a serialized JSON format.</li><li>Sendable This protocol indicates that the type can be safely used in concurrent code. It’s essential for types that will be used across different threads or tasks, ensuring that they don’t cause data races or concurrency issues.</li></ul><p><strong>Functionality</strong></p><ul><li>URL Request Validation The method first checks if the endpoint provides a valid URL request. If not, it throws an APIClientError.invalidURL, indicating a configuration issue.</li><li>Perform Network Request It uses performRequest private method to execute the network call and retrieve the response data asynchronously. This method handles the actual communication with the server.</li><li>Decode Response Data The method attempts to decode the received data into the generic type T using the decoder. If decoding fails, it throws an APIClientError, providing details about the failure.</li></ul><p>The APIClient also has additional methods for different use cases</p><ul><li><strong>Request Void</strong> method, in cases when we only are interested in the request status (success or failure).</li><li><strong>Request through Alamofire</strong>, which I do not recommend, but just in case you are a fan of our beloved framework from the past.</li><li>Request method that we want to <strong>get the request-response Data</strong>, in case we need to decode it differently.</li></ul><h4>Network Interceptor (<a href="https://github.com/egzonpllana/NetworkLayerSwift6/blob/main/NetworkingLayerSwift6/Architecture/Infrastructure/Networking/Protocols/NetworkInterceptor.swift">GitHub</a>)</h4><p><strong>What is a Network Interceptor?<br></strong>It is a component that allows you to modify or inspect outgoing requests and incoming responses in a networking layer. It acts as a middleware between the APIClient and the actual network request execution.</p><p><strong>Network Interceptors can:</strong><br>- Modify requests before they are sent (e.g., adding headers, and authentication tokens).<br>- Log requests and responses for debugging.<br>- Retry failed requests automatically.<br>- Enforce timeouts or custom error-handling strategies.</p><p><strong>When to use<br></strong>Use Network Interceptors when you need to:<br>- Standardize authentication by injecting tokens into every request.<br>- Log network activity without modifying the APIClient logic.<br>- Handle automatic retries for specific failure conditions.<br>- Add request-specific configurations dynamically.</p><p><strong>Example: Adding Headers with a Network Interceptor<br></strong>A common use case for interceptors is injecting headers (such as authorization tokens or custom identifiers) into every request.</p><pre>struct HeaderInjectorInterceptor: NetworkInterceptor {<br>    private let headers: [String: String]<br><br>    init(headers: [String: String]) {<br>        self.headers = headers<br>    }<br><br>    func intercept(_ request: URLRequest) -&gt; URLRequest {<br>        var modifiedRequest = request<br>        headers.forEach { key, value in<br>            modifiedRequest.setValue(value, forHTTPHeaderField: key)<br>        }<br>        return modifiedRequest<br>    }<br>}<br><br>// Usage in APIClient:<br>let apiClient = APIClient(interceptors: [<br>    HeaderInjectorInterceptor(headers: [&quot;Authorization&quot;: &quot;Bearer my_token&quot;])<br>])</pre><h4>Real app implementation (<a href="https://github.com/egzonpllana/NetworkLayerSwift6/tree/main/NetworkingLayerSwift6/Architecture/Presentation/Home">GitHub</a>)</h4><p>In this example, HomeViewModel leverages APIClient to handle network requests and update its posts property with the data fetched from an API.</p><pre>class HomeViewModel: ObservableObject {<br>  @Published var posts: [PostDTO] = []<br>  private let apiClient: APIClientProtocol = APIClient()<br><br>  func getPosts() async throws {<br>       posts = try await apiClient.request(APIEndpoint.getPosts)<br>   }<br>}</pre><ul><li>The class is marked as ObservableObject, which allows SwiftUI views to observe changes in its properties.</li><li>The @Published modifier is used on the posts property so that the UI automatically updates whenever the value changes.</li><li>The apiClient is an instance of APIClient, which conforms to APIClientProtocol and handles all network interactions.</li></ul><p>The getPosts() method demonstrates how APIClient interacts with an API endpoint:</p><ul><li>request(APIEndpoint.getPosts) sends a request to the getPosts endpoint, using the request(_:decoder:) method from APIClientProtocol.</li><li>The result is decoded into an array of PostDTO and then assigned to the posts property.</li><li>This operation is performed asynchronously using Swift’s async/await, making it efficient and non-blocking.</li></ul><p>In this example, HomeView is a SwiftUI view that displays the number of posts fetched from an API using HomeViewModeland APIClient.</p><pre>struct HomeView: View {<br> @StateObject private var viewModel = HomeViewModel()<br> <br> var body: some View {<br>    Text(&quot;Posts count: \(viewModel.posts.count)&quot;)<br> }<br> .onAppear {<br>    Task {<br>        try await viewModel.getPosts()<br>    }<br> }<br>}</pre><ul><li>HomeView uses @StateObject to create and manage the viewModel instance, which is responsible for handling data fetching.</li><li>The body of the view contains a simple Text element that displays the count of posts from the viewModel.</li></ul><p>In the .onAppear modifier:</p><ul><li>A Task block is created to perform the asynchronous viewModel.getPosts() call. This ensures that the posts are fetched when the view appears on the screen.</li><li>Inside the task, viewModel.getPosts() is called asynchronously, requesting the API to retrieve posts via the APIClient. The posts array in HomeViewModel is updated when the data is successfully fetched, and the UI reflects the new data automatically due to the @Published property.</li></ul><p>Now you can find the full implementation of the Networking layer alongside example usage in a small app with ViewModel in SwiftUI, and unit test coverage for the APIClient and APIEndpoint. Click <a href="https://github.com/egzonpllana/NetworkLayerSwift6">here</a> to get redirected to the GitHub repository.</p><p>Isn’t this the most beautiful Networking layer you have ever seen? If yes, let&#39;s go an extra mile to understand concurrency and thread-safe techniques in Swift👇🚀</p><blockquote>Additionally you can read <a href="https://medium.com/@egzonpllana/understanding-concurrency-in-swift-6-with-sendable-protocol-mainactor-and-async-await-5ccfdc0ca2b6">Understanding Concurrency in Swift 6 with Sendable Protocol, MainActor, and async-await</a>.</blockquote><h3>The end 🏁</h3><p>I hope you found this article both engaging and useful for your projects. Personally, I have successfully applied these techniques in my projects and technical challenges for different companies without any issues. You can customize and extend the methods as needed while utilizing generics to maintain code efficiency. Asynchronous programming with Sendable and async/await is likely to become a standard practice in the near future for any Apple platform.</p><p>Thank you for following along. I encourage you to share any feedback or suggestions you may have about this Networking Layer. Together, we can continue to enhance and refine it.</p><h3>Resources</h3><p><a href="https://developer.apple.com/documentation/Swift/MainActor?changes=__7">MainActor</a> by Apple <br><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/">Concurrency</a> <em>by Apple</em> <br><a href="https://developer.apple.com/documentation/swift/sendable#">Sendable protocol</a><em> by Apple</em></p><h3>GitHub</h3><p>Find the full implementation in the GitHub repository:<br><a href="https://github.com/egzonpllana/NetworkLayerSwift6/tree/main">https://github.com/egzonpllana/NetworkLayerSwift6</a></p><p>EventHorizon package on GitHub:<br><a href="https://github.com/egzonpllana/EventHorizon">https://github.com/egzonpllana/EventHorizon</a></p><h3>Let’s Connect</h3><ul><li>LinkedIn: <br><a href="https://www.linkedin.com/in/egzon-pllana">https://www.linkedin.com/in/egzon-pllana</a></li><li>GitHub: <br><a href="https://github.com/egzonpllana">https://github.com/egzonpllana</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=927fa1d0cce8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>