<?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 Will Lumley on Medium]]></title>
        <description><![CDATA[Stories by Will Lumley on Medium]]></description>
        <link>https://medium.com/@will-lumley?source=rss-7dd3527490eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kNKYbLdrKEJrK7o8gmJDlQ.png</url>
            <title>Stories by Will Lumley on Medium</title>
            <link>https://medium.com/@will-lumley?source=rss-7dd3527490eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:15:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@will-lumley/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[Enums. Swift’s Secret Superpower.]]></title>
            <link>https://levelup.gitconnected.com/enums-swifts-secret-superpower-4dc7b048b551?source=rss-7dd3527490eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dc7b048b551</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Will Lumley]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 17:24:52 GMT</pubDate>
            <atom:updated>2026-04-29T14:48:08.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RCyD1tLTN4EcDzq8.jpg" /></figure><p>If you’ve come from a language like Java, C#, or even Objective-C, you might think you know what an enum is.</p><p>A list of named constants. An integer with a pretty label. Something you use for a switch statement and then forget about.</p><p>That’s not what Swift enums are.</p><p>Swift enums are one of the most expressive, flexible, and genuinely powerful tools in the entire language. Once you really understand them, once you stop thinking of them as fancy integers — they’ll change the way you model data, handle errors, and architect your apps.</p><p>You might think I’m just overhyping it or being dramatic, but let me show you what I mean.</p><h3>The Basics (Stick With Me)</h3><p>Yes, Swift enums can be a simple list of cases. You know this part.</p><p>Fine. But this isn’t what makes them interesting. What makes them interesting is everything else.</p><h3>Associated Values: Enums That Carry Data</h3><p>Here’s where things start getting fun.</p><p>Swift enums can have <strong>associated values</strong> — each case can carry its own payload of data, and each case can carry <em>different</em> data.</p><p>Think about what just happened here. We’ve modelled an entire domain concept (payment methods) in a single type. Each case captures exactly the data it needs and nothing more. A creditCard needs card details. applePay needs nothing. There&#39;s no awkward optional properties that may or may not be set depending on which &quot;type&quot; this object happens to be.</p><p>You can extract the associated values with pattern matching:</p><p>Clean, readable, and exhaustive. The compiler won’t let you forget a case.</p><h3>The compiler has your back</h3><p>This is where enums quietly become a design tool rather than just a language feature. Because Swift enforces exhaustive switch statements, every possible case must be handled at compile time. That means if you add a new case to an enum, the compiler immediately flags every place in your codebase that hasn’t accounted for it yet.</p><p>What would normally be a subtle runtime bug-something silently falling through the cracks-gets turned into a loud, actionable compiler error. Instead of relying on discipline, conventions, or test coverage to catch missing logic, the language itself guarantees it. As your app grows and evolves, that safety net becomes incredibly valuable: your model changes, and the compiler walks you directly to every piece of code that needs to change with it.</p><h3>Raw Values: Enums That Map to Primitives</h3><p>On the flip side, sometimes you <em>do</em> want that integer-or-string-underneath behaviour. Swift supports this too, via <strong>raw values</strong>.</p><p>You can initialise from a raw value (carefully — it’s failable):</p><p>Raw values work with String too, which is incredibly useful when you&#39;re decoding JSON:</p><p>Because UserRole conforms to Codable, any struct or class that contains a UserRole property can encode and decode it automatically. The raw string value is used in the JSON. No boilerplate. No custom decoder. It just works.</p><h3>Computed Properties and Methods</h3><p>Here’s something that might surprise you: <strong>Swift enums can have methods and computed properties.</strong></p><p>They’re not just passive data containers. They can carry behaviour.</p><p>Now your Suit enum is a self-contained, intelligent type. You&#39;re not writing if suit == .hearts || suit == .diamonds scattered around your codebase - the logic lives right where it belongs.</p><h3>Enums and Error Handling</h3><p>Swift’s Error protocol pairs beautifully with enums, and I&#39;d argue it&#39;s one of the best error modelling stories in any mainstream language.</p><p>Look how much information is packed in there. A requestFailed error carries the status code. A decodingFailed error wraps the underlying parsing error so you don&#39;t lose it. And at the call site, you handle each case deliberately:</p><p>Compare this to returning nil and hoping the caller figures it out, or passing back an NSError with a userInfo dictionary. Swift enum errors are explicit, typed, and a joy to handle.</p><h3>Recursive Enums</h3><p>Okay, this one is a bit of a mind-bender. Swift enums can be <em>recursive</em> — a case can contain an associated value of the same enum type. You opt into this with the indirect keyword.</p><p>The classic example is a linked list:</p><p>Or an expression tree:</p><p>You probably won’t reach for this every day, but when you need it — say, when modelling a tree structure or a recursive data format — it’s incredibly elegant. No class hierarchies, no protocols, no inheritance chains. Just an enum.</p><h3>The Real Superpower: Replacing Class Hierarchies</h3><p>Here’s the thing that took me a while to fully appreciate.</p><p>In other languages, if you want to model “a thing that can be one of several different shapes”, you typically reach for class inheritance or interfaces. You end up with a base class, a bunch of subclasses, and a lot of is checks or virtual dispatch.</p><p>Swift enums let you throw all of that away.</p><p>Consider a notification system for an app. In an OOP-heavy approach, you might have a Notification base class with PushNotification, EmailNotification, and SMSNotification subclasses. Checking the type at runtime, casting, maybe a visitor pattern to avoid if chains&amp;mldr;</p><p>In Swift:</p><p>The switch is exhaustive. If you add a new notification type later, the compiler will point at every switch statement that needs updating. You can&#39;t accidentally forget to handle a new case.</p><p>That’s a guarantee that inheritance simply cannot give you.</p><h3>A Pattern Worth Knowing: Enums as State</h3><p>One of my favourite uses of enums in practice is modelling <strong>view state</strong>. Instead of scattering optional properties and boolean flags around your view model, you can represent the entire state of a screen as a single enum:</p><p>Then in your view model:</p><p>And in your view, you switch on state to render exactly the right UI for exactly the right situation. No isLoading: Bool. No user: User? sitting next to an error: Error?. Just one source of truth.</p><h3>Versus Kotlin’s Sealed Interfaces</h3><p>At this point, if you’re a Kotlin developer reading over someone’s shoulder (or one of my poor coworkers who got hit with my rant on how goated Swift’s enums are), you might be thinking: “Okay, but Kotlin has sealed interfaces. Isn’t this basically the same thing?”</p><p>It’s a fair question. And the honest answer is: sealed interfaces are great, and Kotlin deserves credit for having them. But they’re not the same, and the differences matter.</p><p>In Kotlin, to model our PaymentMethod example from earlier, you&#39;d write something like this:</p><p>That works. The when expression is exhaustive, the compiler enforces it, and you get the same safety guarantees at the call site. No argument there.</p><p>But look at what you had to write to get there.</p><p>For each “case”, you’ve declared a full class — either a data class or an object. That means each variant is its own separate type, with its own file conventions, its own inheritance chain, its own potential for being subclassed or misused elsewhere. It&#39;s a collection of classes wearing a sealed interface as a uniform.</p><p>Swift’s enum is a single, unified type. There’s no class involved. No inheritance. No object singleton for the payload-free cases. You write one enum block and you&#39;re done:</p><p>The difference in noise is obvious. But the more important difference is conceptual.</p><p>Kotlin’s sealed interface is a <strong>hierarchy</strong> — it’s inheritance with a restricted family tree. Swift’s enum is an <strong>algebraic data type</strong> — it’s a value that is exactly one of a fixed set of possibilities, with no inheritance, no polymorphism, and no open questions about what else might be lurking in the codebase.</p><p>This has practical consequences. With a Kotlin sealed interface, each subclass can independently implement methods, add new properties, and conform to additional interfaces. That flexibility is sometimes useful. But it also means the cases aren’t really equal citizens of a single concept — they’re separate types that happen to share a parent.</p><p>With a Swift enum, all cases are literally part of the same type. Methods and computed properties are defined once, on the enum itself, and they apply uniformly across all cases. There’s no risk of one subclass “forgetting” to override a method, or implementing the protocol slightly differently from its sibling.</p><p>There’s also the matter of <strong>raw values</strong>, which sealed interfaces simply don’t have an equivalent for. You can’t write:</p><p>But in Swift:</p><p>Works perfectly, including failable initialisation from a raw integer and automatic Codable synthesis.</p><p>To be fair to Kotlin, sealed interfaces do have one genuine advantage: because each case is its own class, they can each hold mutable state, implement their own interfaces independently, and be extended in more complex ways. If you need that flexibility, sealed interfaces deliver it.</p><p>But for the vast majority of use cases — modelling states, errors, configurations, API responses — that flexibility isn’t something you need. It’s complexity you’re carrying around for no reason.</p><p>Swift enums give you the right amount of power for the job. Nothing more, nothing less.</p><h3>Wrapping Up</h3><p>Swift enums are not a list of named constants.</p><p>They’re a tool for modelling state exhaustively, carrying typed data without optional pollution, expressing errors meaningfully, and replacing entire class hierarchies with something simpler and safer.</p><p>Once you start thinking in enums, you’ll notice yourself reaching for them constantly — for API responses, navigation paths, UI state, error handling, configuration. They’re everywhere once you see them.</p><p>And the best part? The Swift compiler has your back the whole way. Exhaustive switch statements mean that when your model changes, the compiler finds every place that needs updating. That’s a safety net that scales.</p><p>If there’s one feature I’d point to and say “this is what makes Swift genuinely great to write”, it’s this. Enums are Swift’s superpower.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dc7b048b551" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/enums-swifts-secret-superpower-4dc7b048b551">Enums. Swift’s Secret Superpower.</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[How I Turned My Broken Garage Remote Into a HomeKit Garage Door for Under $22]]></title>
            <link>https://levelup.gitconnected.com/how-i-turned-my-broken-garage-remote-into-a-homekit-garage-door-for-under-22-38465ac6080a?source=rss-7dd3527490eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/38465ac6080a</guid>
            <category><![CDATA[electronic-engineering]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Will Lumley]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 17:24:54 GMT</pubDate>
            <atom:updated>2025-12-10T07:21:02.799Z</atom:updated>
            <content:encoded><![CDATA[<p>A few weeks ago, my garage remote died. Completely. No LED, no click, no signs of life even after replacing the battery.</p><p>Normally, this would be annoying enough, but my house relies heavily on HomeKit. Lights, blinds, cameras, fans - everything responds to Siri&amp;mldr; except the garage. And now, even the dumb remote wasn’t working.</p><p>But instead of buying a $90 replacement remote or a $250 HomeKit-enabled garage opener, I had a different thought:</p><p>What if I use this as an opportunity to learn something&amp;mldr; and make my garage smart while I’m at it?</p><p>So that’s exactly what I did.</p><p>For less than $22 AUD, I turned my dumb garage door opener into a fully HomeKit-compatible accessory using an ESP32, a relay, a DC to DC buck converter, some careful wiring, and my own custom firmware.</p><p>The first half of this post will go through the hardware side of things:</p><ul><li>How garage door openers work</li><li>What parts you need</li><li>How to wire everything</li><li>Real photos from my build</li><li>Troubleshooting tips</li></ul><p>In the second half I’ll go through the software side of things - but if you don’t want to bother with that I’ll also post the entire source code as a public GitHub repository (with a proper README, build instructions, and maybe even a few example configs) so you can just clone and run it right away.</p><h3>The Hardware</h3><h3>🧠 Understanding Your Garage Door Opener</h3><p>Even “dumb” garage door openers are surprisingly simple. They’re almost always controlled by a momentary short between two terminals:</p><ol><li>One labelled something like COM, COMMON, or GND</li><li>The other labelled PUSH BUTTON, SW, “NEG SWITCH”, etc.</li></ol><p>Here’s what mine looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Y_Yb3VejAIj7tPE.png" /></figure><p>The wall button in your garage is nothing more than a switch that temporarily connects those two terminals. Short them with a screwdriver, and the door will open or close. This simplicity makes garage doors the perfect HomeKit DIY project — you just need a relay that can simulate a button press.</p><h3>🧩 Parts List (Everything I Used — ~$21 Total)</h3><p>I bought all the components from Temu. Yes, Temu can be hit-or-miss with quality in general, but I’ve been consistently impressed with their basic electronic parts and microcontrollers — everything I’ve received so far has been perfectly usable, correctly specced, and performed just as well as name-brand equivalents, often at a fraction of the price. Your mileage may vary with other categories, but for this kind of project they’ve been spot-on.</p><p>These are the exact parts from my build:</p><p><em>ESP32 Dev Board</em></p><ul><li><a href="https://share.temu.com/xWgaTqWLm9A">https://share.temu.com/xWgaTqWLm9A</a></li><li>$4.97</li><li>Serves as the main microcontroller for the smart garage opener, running the code to connect to Wi-Fi, receive remote commands, and trigger the relay.</li></ul><p><em>DC-DC Buck Converter (24V → 5V)</em></p><ul><li><a href="https://share.temu.com/S7TTOrnP9dA">https://share.temu.com/S7TTOrnP9dA</a></li><li>$4.66</li><li>Steps down the garage door opener’s 24V power supply to a stable 5V to safely power the ESP32 and relay module without risking damage to sensitive electronics.</li></ul><p><em>1 Channel Relay Module</em></p><ul><li><a href="https://share.temu.com/PN6dg31uOSA">https://share.temu.com/PN6dg31uOSA</a></li><li>$5.78</li><li>Acts as the high-voltage switch to activate the garage door opener’s motor circuit when signaled by the ESP32, allowing low-voltage control of the 24V garage hardware.</li></ul><p><em>Breadboard</em></p><ul><li><a href="https://share.temu.com/zobt7wqzyaA">https://share.temu.com/zobt7wqzyaA</a></li><li>$2.99</li><li>Provides a solderless prototyping platform for assembling and testing the circuit connections between the ESP32, relay, converter, and wiring.</li></ul><h3>🔌 Step 1 — Mounting and Power</h3><p>Most garage openers provide +24V and GND for accessories. In my garage, the GND was labelled as COM WALL. Here’s my buck converter + ESP32 setup:</p><pre>Garage +24V → Buck Converter VIN+ <br>Garage COMWALL → Buck Converter VIN−</pre><p>In case you’re confused, VIN stands for Vault Input and GND stands for Ground.</p><p>So what this does is gets the 24 voltage from the garage, and turns it down to 5 volts — which is the voltage level our ESP32 can take in without frying. This keeps everything powered 24/7 without needing a separate wall charger.</p><p>So right now we have our DC Buck Converter taking in 24 volts and stepping it down to 5 volts. Let’s now connect our Buck Converter to our ESP32 so we can safely power it.</p><pre>Buck Converter OUT 5V → ESP32 VIN <br>Buck Converter OUT GND → ESP32 GND</pre><h3>🪛 Step 2 — Wiring the ESP32 and Relay</h3><p>Now that the ESP32 is safely powered from the buck converter, the next step is wiring it to the relay module so it can actually control when the garage door opens or closes.</p><p>The ESP32 can only output a tiny 3.3V signal — nowhere near enough to directly trigger the garage opener’s switch terminals. So instead, we give it a helper: a 1-Channel Relay Module.</p><p>Think of the relay as a programmable finger.</p><p>When the ESP32 tells it to activate, the relay “presses the button” by closing its internal contacts.</p><p>A relay module has two sides:</p><ul><li>Input Side — where the ESP32 tells the relay to switch</li><li>Output Side — the screw terminals that will connect to the garage opener (we’ll handle these in Step 3)</li></ul><p>For now, we’re wiring only the input side.</p><p>Most relay modules have these pins on the input:</p><p>Here’s how to wire it:</p><pre>ESP32 5V → Relay VCC ESP32<br>GND → Relay GND ESP32 <br>GPIO22 (or any spare digital pin) → Relay IN</pre><p>It doesn’t have to be GPIO22 — you can use almost any free digital pin. I chose 22 because:</p><p>Once this is connected, the ESP32 can activate the relay by simply driving the IN pin HIGH.</p><p>That’s all there is to it — the relay now has power, and the ESP32 officially controls a physical output on your garage hardware.</p><p>At this point:</p><p>But the relay isn’t actually connected to the garage door yet — all we’ve done is set up the control side.</p><p>That part comes next.</p><h3>🛠️ Step 3 — Wiring the Relay to the Garage Door</h3><p>With the relay now under the ESP32’s control, it’s finally time to connect it to the garage door opener itself. This is the part that makes the whole project actually do something.</p><p>Every garage door opener has two terminals dedicated to the wall button. When you press the button on the wall, you’re not sending a voltage — you’re simply shorting those two terminals together momentarily.</p><p>On my opener, these terminals were labelled:</p><p>Your opener may use slightly different names, but the concept is always the same: one is a common ground, one is the trigger.</p><p>A relay module has three screw terminals on its output side:</p><p>For garage door openers, we always use COM and NO.</p><p>NO stays “open” (disconnected) until the ESP32 activates the relay, which temporarily closes the circuit — just like pressing the button on the wall.</p><p>Here’s the exact wiring:</p><pre>Relay COM → COM WALL (Garage Opener) <br>Relay NO  → NEG SWITCH (Garage Opener)</pre><p>And here’s what it looks like in my build:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TpRb8SHaqnlAKFX9.png" /></figure><p>When the relay activates, the NO terminal closes to COM for about one second, triggering the door to open or close. When the relay deactivates, the terminals separate again, preventing multiple toggles.</p><p>This wiring is simple, but it’s the true magic of the entire project — the moment your ESP32 gains the ability to physically control the garage door.</p><p>A clean wire diagram can be seen here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4j4ni03NIgey5hQC.png" /></figure><h3>The Software</h3><p>Now comes the fun part — teaching the ESP32 to speak HomeKit.</p><p>This section is all about the firmware:</p><ul><li>Connecting the ESP32 to Wi-Fi</li><li>Creating a HomeKit Garage Door accessory</li><li>Handling open/close requests</li><li>Triggering the relay</li><li>Keeping HomeKit updated with the correct door state</li><li>Debugging via Serial</li><li>Flashing the firmware onto your ESP32</li></ul><h3>💾 Getting the Code</h3><p>If you don’t want to mess around with writing this code from scratch, that’s totally fair. You can download the source code as is, here:</p><p><a href="https://github.com/will-lumley/GarageDoorOpener-ESP32">https://github.com/will-lumley/GarageDoorOpener-ESP32</a></p><p>The repo includes:</p><p>If you just want your door to open in the Home app, clone the repo and flash it. If you want to learn how everything works, keep reading!</p><p>The IDE we’ll be using is <strong>Arduino IDE</strong>, which you can download from:</p><p><a href="https://www.arduino.cc/en/software/">https://www.arduino.cc/en/software/</a></p><p>I recommend downloading the source code first, and then following along as I explain the important chunks.</p><h3>🍏 Why Use HomeSpan?</h3><p>To expose a device to Apple HomeKit, manufacturers normally need:</p><ul><li>Apple’s MFi chips</li><li>Auth co-processors</li><li>Licensing agreements</li><li>A full security compliance test suite</li></ul><p>HomeSpan bypasses all of that by implementing Apple’s HAP protocol directly on the ESP32.</p><p>It’s local, private, extremely fast, and works beautifully.</p><p>With HomeSpan:</p><ul><li>The ESP32 becomes a full HomeKit accessory</li><li>Siri can open/close the door</li><li>Automations work (e.g. “Open when I arrive home”)</li><li>Everything stays in your local network (no cloud)</li></ul><p>If you’ve ever used commercial HomeKit garage openers, this behaves identically.</p><h3>🧱 Firmware Overview</h3><p>Here’s what the code does in plain English:</p><ol><li>Boot ESP32</li><li>Connect to Wi-Fi</li><li>Start HomeSpan and advertise a “Garage Door Opener”</li><li>Listen for HomeKit commands</li><li>When HomeKit requests <strong>open</strong>:</li><li>Update the door state to Opening</li></ol><ul><li>Pulse the relay</li><li>Update the state to Open</li></ul><ol><li>When HomeKit requests <strong>close</strong>, do the same in reverse</li><li>Keep reporting real-time status to HomeKit</li></ol><p>The implementation is surprisingly small thanks to HomeSpan’s clean APIs.</p><h3>🧩 The Garage Door Accessory Class</h3><p>This class exposes the correct HomeKit characteristics:</p><p>And handles the transition logic.</p><pre>struct GarageDoorAccessory : Service::GarageDoorOpener { <br>  using Function = std::function&lt;void()&gt;; <br><br>  Characteristic::CurrentDoorState *currentState;<br>  Characteristic::TargetDoorState *targetState; <br><br>  SpanCharacteristic *obstruction; <br>  <br>  Function onOpen; <br>  Function onClose; <br><br>  GarageDoorAccessory() : Service::GarageDoorOpener() { <br>    currentState = new Characteristic::CurrentDoorState(<br>      Characteristic::CurrentDoorState::CLOSED<br>    );<br><br>    targetState = new Characteristic::TargetDoorState(<br>      Characteristic::TargetDoorState::CLOSED<br>    ); <br><br>    obstruction = new Characteristic::ObstructionDetected(false); <br>} <br><br>void open() {<br>  targetState-&gt;setVal(Characteristic::TargetDoorState::OPEN); <br>  update(); <br>} <br><br>void close() { <br>  targetState-&gt;setVal(Characteristic::TargetDoorState::CLOSED);\<br>  update(); <br>} <br><br>boolean GarageDoorAccessory::update() {<br>  if (targetState-&gt;getNewVal() == targetState-&gt;OPEN) {<br>    Serial.println(&quot;* Opening Garage Door.&quot;);<br>    currentState-&gt;setVal(currentState-&gt;OPENING);<br>    obstruction-&gt;setVal(false);<br><br>    if (onOpen) {<br>      onOpen();<br>    }<br>  } else {<br>    Serial.println(&quot;* Closing Garage Door.&quot;);<br>    currentState-&gt;setVal(currentState-&gt;CLOSING);<br>    obstruction-&gt;setVal(false);<br><br>    if (onClose) {<br>      onClose();<br>    }<br>  }<br><br>  return true;<br>}</pre><p>This is the exact behaviour Apple expects for a garage door accessory.</p><h3>🔁 Relay Control Logic</h3><p>This triggers the garage opener.</p><pre>void toggleRelayPin() {<br>  pinMode(RELAY_PIN, OUTPUT);<br>  digitalWrite(RELAY_PIN, HIGH);<br>  delay(1000);<br>  digitalWrite(RELAY_PIN, LOW);<br>  pinMode(RELAY_PIN, 0x00);<br>}</pre><h3>📡 Wi-Fi &amp; HomeKit Setup</h3><pre>homeSpan.setPairingCode(&quot;11112222&quot;); <br>homeSpan.setWifiCredentials(ssidChar, passChar); <br>homeSpan.begin(Category::GarageDoorOpeners, &quot;Garage Door&quot;);</pre><p>When this runs, the ESP32 appears in the Home app just like a certified accessory.</p><p>Here’s what pairing looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EoKEBCvDEE1fBIY4.png" /></figure><h3>🧭 Door State Timing</h3><p>HomeKit expects realistic transitions — not instant jumps. This loop updates the state after a delay:</p><pre>void loop() { if (currentState-&gt;getVal() == targetState-&gt;getVal()) return; if (targetState-&gt;timeVal() &gt; 5000) { currentState-&gt;setVal(targetState-&gt;getVal()); } }</pre><p>You can adjust 5000 ms for faster or slower doors.</p><h3>🧪 Flashing the Firmware</h3><p>Okay, now it’s time to compile the code and push the binary onto the ESP32 itself.</p><p>We’ll be using the Arduino IDE to do this.</p><p>Our first step here will be to install ESP32 support for our Arduino IDE.</p><ul><li>Go to File &gt; Preferences (on Windows/Linux) or Arduino IDE &gt; Preferences (on macOS).</li><li>Find the “Additional Boards Manager URLs” field and add <a href="https://espressif.github.io/arduino-esp32/package_esp32_index.json">https://espressif.github.io/arduino-esp32/package_esp32_index.json</a></li><li>Select the “OK” button</li><li>Go to Tools &gt; Board &gt; Boards Manager</li><li>In the Boards Manager, type “ESP32” into the search bar</li><li>Find “esp32 by Espressif Systems” in the search results</li><li>Click the “Install” button next to it.</li></ul><p>Once this is done, open up the garage-door-opener.ino that was in the Github repo, select the ESP32 device in the top toolbar, and press the &quot;Upload&quot; button.</p><h3>🏁 The End Project</h3><p>After everything was wired, flashed, paired, and tucked neatly back into the garage opener housing, the moment of truth finally arrived. I opened the Home app, tapped the new Garage Door accessory… and the relay clicked, the motor hummed, and the door started lifting exactly as it should.</p><p>It felt kind of surreal watching this old, very dumb piece of hardware respond instantly to Siri and HomeKit — and all powered by a $5 ESP32 and a few lines of firmware I wrote myself. No cloud APIs, no subscriptions, no vendor lock-in. Just a clean, local, reliable smart upgrade that I completely control.</p><p>In the video below, you’ll notice a little voltage meter sitting next to the ESP32. That wasn’t part of the final design — I added it temporarily while troubleshooting some weird voltage drops coming from the garage opener’s 24V supply. Under load, the voltage would momentarily dip lower than expected, and I wanted to be absolutely sure the ESP32 wasn’t browning out or rebooting mid-operation. The meter helped confirm that the buck converter was regulating cleanly and that the ESP32 was staying rock-solid throughout the relay pulses. Once everything proved stable, the meter came out and the project was fully enclosed.</p><p>What I love most about this project is how simple it actually is once you understand the pieces. A momentary switch, a relay, a microcontroller, and Apple’s HomeSpan framework - that’s all it takes to breathe new life into an aging garage opener.</p><p>Here’s the final setup in action:</p><p><a href="https://lumley.io/images/blogs/smart-garage/4_Live.MOV">https://lumley.io/images/blogs/smart-garage/4_Live.MOV</a></p><p><em>Originally published at </em><a href="https://lumley.io/blogs/smart-garage/"><em>https://lumley.io</em></a><em> on December 2, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38465ac6080a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-i-turned-my-broken-garage-remote-into-a-homekit-garage-door-for-under-22-38465ac6080a">How I Turned My Broken Garage Remote Into a HomeKit Garage Door for Under $22</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[AsyncCombine: Because Async Code Shouldn’t Be Ugly]]></title>
            <link>https://levelup.gitconnected.com/asynccombine-because-async-code-shouldnt-be-ugly-43915f71b921?source=rss-7dd3527490eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/43915f71b921</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[swift-async-await]]></category>
            <category><![CDATA[combine]]></category>
            <dc:creator><![CDATA[Will Lumley]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 17:24:16 GMT</pubDate>
            <atom:updated>2025-10-03T02:41:00.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o49zX9EB8DplKCTc.png" /></figure><h3>Introducing Combine</h3><p>When Swift first introduced Combine, I loved it. The syntax was expressive, pipelines were easy to follow, and @Published made state changes feel almost magical. But as Apple pushed us toward Swift Concurrency, I decided to bite the bullet and migrate one of my apps away from Combine.</p><p>The migration worked; async/await is powerful, predictable, and in many ways simpler. But I quickly noticed something, parts of my code just weren’t as easy to read anymore. A neat Combine one-liner became a few clunky async calls. And to make things worse, I couldn’t rely on @Published to observe changes between view models anymore.</p><p>Here’s a concrete example. Here’s a view model you might see before the @Observable macro was implemented.</p><p>The @Published property wrapper makes it easy to bind properties to SwiftUI views - and equally easy to observe those properties from other view models. The @Published property wrapper essentially turns a property into a lightweight publisher; every time the value changes, anyone subscribed is instantly notified.</p><p>This makes it trivial to wire up relationships like:</p><p>Or if you wanted, you could map the published value and assign it to another view model’s property, like so:</p><p>And just like that, you have LoggerViewModel&#39;s countDescription automatically listen in to any CounterViewModel&#39;s count property updates, map the value, and either log it or assign the transformed value to itself.</p><p>Amazing, right?</p><h3>Introducing Swift Concurrency</h3><p>With the release of swift-async-algorithms and the fact that Combine hasn&#39;t really seen a meaningful update since 2020, it&#39;s pretty clear where Apple wants us to head: Swift Concurrency is the future.</p><p>And honestly, that’s a good thing. Async/await gives us structured concurrency, language-level cancellation, and AsyncSequence as a powerful primitive for streams. It&#39;s predictable, modern, and way less error-prone than callback hell or juggling Combine operators that sometimes felt&amp;mldr; magical in ways you didn&#39;t always want.</p><p>To add onto this, Combine is a library that exists only in the Apple ecosystem. This means you can’t use it in Swift programs that target Windows/Linux, and you can’t use it in anything server-side. Compare this to Swift Concurrency, which exists as a set of first-class citizens baked into the Swift language itself, and you can start to see the appeal.</p><p>Now, to be fair, if all you need is ViewModel to SwiftUI View data updates, Swift Concurrency already has a great story. With the new @Observable macro, property changes in your models can automatically drive SwiftUI updates, and it feels every bit as smooth as @Published did.</p><p>But where things get messy is ViewModel to ViewModel data updates. That’s where you start to feel the loss of Combine. There’s no built-in equivalent of subscribing to another object’s property updates. There’s no $count publisher you can just sink or assign. You&#39;re left rolling your own AsyncStream wrappers or juggling manual task loops, and the ergonomics take a big hit.</p><p>So yes, Swift Concurrency is the future&amp;mldr; but moving from Combine isn’t always painless.</p><p>Let’s go back to our CounterViewModel. With Combine, we saw how easy it was to sink or assign its @Published values. With Swift Concurrency alone, that turns into something like this:</p><p>It works. It’s correct. It’s platform-agnostic. But it’s not elegant.</p><p>Suddenly you’re manually managing tasks, dealing with for await loops, and if you want to transform or map those values, you’re either nesting more loops or pulling in swift-async-algorithms. And while async algorithms are powerful, the resulting code doesn’t read as cleanly as a Combine pipeline.</p><p>The end result? Readability takes a hit. That neat, declarative one-liner you had in Combine now feels heavier and harder to scan at a glance.</p><p>And that’s before you start talking about missing operators like CombineLatest, or primitives like CurrentValueSubject.</p><p>This is where I started thinking: what if I could bring back Combine’s expressive syntax; but reimagine it for Swift Concurrency?</p><h3>Introducing AsyncCombine</h3><p>That frustration is what led me to build AsyncCombine. The idea was simple: keep the async/await foundations that Apple clearly wants us to use, but bring back the clean, chainable operators that made Combine such a joy to write.</p><p>AsyncCombine gives you familiar tools like sink, assign, and store(in:), rebuilt on top of AsyncSequence and Swift&#39;s new Observation framework. That means you get the readability of Combine, but without relying on Combine itself. And because it&#39;s just Swift Concurrency under the hood, it works on iOS, macOS, and even Linux.</p><p>Here’s our CounterViewModel and LoggerViewModel example again, but written with AsyncCombine:</p><p>Notice how this looks and feels almost exactly like the Combine version? No manual Task, no for await loop; just a declarative pipeline that you can scan at a glance.</p><p>And it’s not just sink. AsyncCombine builds on Swift Concurrency and works seamlessly with swift-async-algorithms, giving you operators like map, filter, merge, throttle, and removeDuplicates out of the box.</p><p>and, in my biased opinion, is much more elegant than:</p><p>Feels like Combine again, but async/await-native. 🚀</p><h3>Rebuilding the Missing Pieces</h3><p>AsyncCombine isn’t just about nicer syntax. Once I started leaning on it in real apps, I realized there were some fundamental building blocks from Combine that I really missed. Two in particular: CurrentValueSubject and Publishers.CombineLatest(_, _:).</p><h3>CurrentValueSubject</h3><p>In Combine, CurrentValueSubject was my go-to whenever I needed a stream that always had a &quot;latest value.&quot; Subscribers would immediately get the current value, then receive future updates. Simple, powerful, and incredibly handy for bridging state between layers.</p><p>Swift Concurrency doesn’t have an equivalent; so I built CurrentValueRelay. It&#39;s a replay-1 async primitive: every subscriber instantly sees the most recent value, then stays up-to-date as new values come in.</p><p>The output of the above would be:</p><p>This makes CurrentValueRelay perfect for keeping view models or services in sync, without writing extra boilerplate.</p><h3>Publishers.CombineLatest</h3><p>The other operator I couldn’t live without was Publishers.CombineLatest. It made it so easy to merge two (or more) streams into one, always keeping the latest values in play.</p><p>So AsyncCombine includes a CombineLatest operator for AsyncSequence.</p><p>The output of the above would be:</p><p>Just like in Combine, whenever either upstream produces a value, you get a fresh tuple with the latest from both sides.</p><p>Together, CurrentValueRelay and AsyncCombine.CombineLatest bring back two of Combine&#39;s most powerful patterns - now in an async/await-native form.</p><h3>Why It Matters</h3><p>At this point you might be thinking: “Okay, this is just syntax sugar, right?”</p><p>But in practice, AsyncCombine solves a very real problem: keeping async code readable and expressive.</p><p>Swift Concurrency gives us the strong foundations — structured tasks, cancellation, AsyncSequence - but when your app grows beyond a few isolated Task { &amp;mldr; } blocks, the lack of ergonomic operators starts to show.</p><p>Here’s what AsyncCombine brings back to the table: * Readability — A one-liner .sink { ... } is easier to scan than a for await loop buried inside a task. * Composition - Operators like map, filter, and CombineLatest let you describe intent directly, without hand-wiring streams together. * State bridging - CurrentValueRelay makes it trivial to share &quot;latest state&quot; across layers without bolting on extra machinery. * Cross-view model observation - observed(_:) gives you back the simplicity of listening to another view model&#39;s property updates. * Cross-platform support - Built purely on Swift Concurrency, AsyncCombine works on iOS, macOS, and even Linux/server-side Swift.</p><p>AsyncCombine doesn’t try to replace Swift Concurrency, it complements it. You still get all the benefits of async/await being a first-class part of the language, but with the expressive, declarative style that made Combine so enjoyable to use.</p><p>And because it’s not tied to Apple frameworks, AsyncCombine is lightweight, portable, and future-proof.</p><p>You can check out the source code and integrate AsyncCombine into your projects now.</p><p>👉 <a href="https://github.com/will-lumley/AsyncCombine">Check it out on GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43915f71b921" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/asynccombine-because-async-code-shouldnt-be-ugly-43915f71b921">AsyncCombine: Because Async Code Shouldn’t Be Ugly</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[How to Write Unit Tests for Combine Publishers in Swift Testing]]></title>
            <link>https://levelup.gitconnected.com/how-to-write-unit-tests-for-combine-publishers-in-swift-testing-04b92299d275?source=rss-7dd3527490eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/04b92299d275</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Will Lumley]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 02:19:10 GMT</pubDate>
            <atom:updated>2024-12-02T02:19:10.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*yR1G7iSXRafCK_cNLSKGlg.png" /></figure><p>Unit testing Combine publishers can feel like you’re wrestling with a slippery eel: asynchronous, stateful, and a bit chaotic if not handled correctly. But fear not! Today, I’ll walk you through how to tame these tricky beasts using Swift Testing and its elegant testing features. Whether you’re a seasoned Combine wrangler or new to reactive programming, by the end of this post, you’ll have the tools to confidently write unit tests for your publishers.</p><h4>Why Test Publishers?</h4><p>Combine publishers are at the heart of many modern Swift apps, powering everything from data streams to user interactions. Testing these publishers ensures that your streams emit the correct values, complete as expected, and handle errors gracefully. And with Swift Testing’s clean syntax and tools like #expect and #require, writing these tests becomes a delight instead of a chore.</p><h4><strong>Setting the Stage: What We’ll Test</strong></h4><p>Imagine you’re working on a project with a database manager that has a method for fetching items from the database. Here’s our method under test:</p><pre>func getItemPublisher(by id: Int) -&gt; AnyPublisher&lt;Item, Never&gt; {<br>    items<br>        .filter { $0.id == id }<br>        .eraseToAnyPublisher()<br>}</pre><p>The goal? Ensure this publisher correctly emits the requested item when the database is updated. We’ll write a test for this using Swift Testing that:</p><ol><li>Inserts a new item into the database.</li><li>Subscribes to the getItemPublisher.</li><li>Asserts that the emitted item matches the inserted one.</li></ol><h4>Writing the Test</h4><p>Here’s the code for our test:</p><pre>@Test(&quot;Get Item Publisher&quot;)<br>func getItemPublisher() async throws {<br>    // Create a set to manage our Combine subscriptions<br>    var cancellables: Set&lt;AnyCancellable&gt; = []<br><br>    // GIVEN we have our test subject<br>    let testSubject = DatabaseManager()<br><br>    // GIVEN an item we want to test<br>    let mockItem = Item.mock(id: 1, name: &quot;Test Item&quot;, details: &quot;Details here&quot;)<br>    <br>    // WHEN we insert the mock item into the database<br>    try await testSubject.insert(item: mockItem)<br><br>    // THEN the publisher should emit the correct item<br>    await withCheckedContinuation { continuation in<br>        testSubject.getItemPublisher(by: mockItem.id)<br>            .sink { fetchedItem in<br>                // Assert that the fetched item matches the mock item<br>                #expect(fetchedItem == mockItem)<br><br>                // Finish the test<br>                continuation.resume()<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><h3><strong>Breaking It Down</strong></h3><p>So let’s break down what we just did!</p><h4><strong>Managing Subscriptions</strong></h4><p>In Combine, you need to manage your subscriptions to avoid memory leaks. Here, we use a Set&lt;AnyCancellable&gt; to store our subscription:</p><pre>var cancellables: Set&lt;AnyCancellable&gt; = []</pre><h4><strong>Setting Up the Test Subject</strong></h4><p>We use a mock item and a test instance of our database:</p><pre>let mockItem = Item.mock(id: 1, name: &quot;Test Item&quot;, details: &quot;Details here&quot;)<br>let testSubject = DatabaseManager()</pre><p>Mocking data is essential for tests, as it allows us to control inputs and outputs without relying on external dependencies.</p><h4><strong>Performing the Test</strong></h4><p>The test revolves around inserting the mock item and observing the publisher for the expected output:</p><pre>try await testSubject.insert(item: mockItem)</pre><p>Once the item is inserted, the getItemPublisher should emit the mock item.</p><h4>Asserting the Results</h4><p>Within the sink closure, we use Swift Testing’s handy #expect macro to make assertions:</p><pre>#expect(fetchedItem == mockItem)</pre><p>These ensure the emitted item matches our expectations.</p><h4>Continuation for Async Handling</h4><p>Combine works asynchronously, so we use withCheckedContinuation to integrate Combine with Swift’s async/await syntax:</p><pre>await withCheckedContinuation { continuation in<br>    testSubject.getItemPublisher(by: mockItem.id)<br>        .sink { fetchedItem in<br>            #expect(fetchedItem == mockItem)<br>            continuation.resume()<br>        }<br>        .store(in: &amp;cancellables)<br>}</pre><p>This ensures the test completes only after the publisher emits a value and our assertions are verified.</p><h3>Testing Errors and Edge Cases</h3><p>Combine tests aren’t just about the happy path. You’ll want to test error handling and edge cases as well. Here’s an example for a publisher that emits errors:</p><pre>@Test(&quot;Error Handling Publisher&quot;)<br>func errorPublisher() async throws {<br>    var cancellables: Set&lt;AnyCancellable&gt; = []<br><br>    // GIVEN a faulty publisher<br>    let faultyPublisher = PassthroughSubject&lt;Item, Error&gt;()<br><br>    // WHEN the publisher fails<br>    faultyPublisher.send(completion: .failure(SomeError()))<br><br>    // THEN the test should catch the error<br>    await withCheckedContinuation { continuation in<br>        faultyPublisher<br>            .sink(receiveCompletion: { completion in<br>                if case .failure(let error) = completion {<br>                    #expect(error is SomeError)<br>                    continuation.resume()<br>                }<br>            }, receiveValue: { _ in<br>                Issue.record(&quot;Publisher should not emit a value&quot;)<br>            })<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><h3>Wrapping Up</h3><p>Testing Combine publishers doesn’t have to be daunting. With Swift Testing’s powerful macros and the structured approach we explored today, you can write clean, effective tests that validate your reactive streams.</p><p>Remember, the key to mastering Combine testing lies in:</p><ol><li>Managing subscriptions effectively.</li><li>Asserting values and errors with precision.</li><li>Leveraging tools like withCheckedContinuation to integrate with async/await.</li></ol><p>Go ahead, write your tests, and let your Combine code shine with confidence! And if you’re stuck, drop a comment or reach out — I’d love to help.</p><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04b92299d275" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-write-unit-tests-for-combine-publishers-in-swift-testing-04b92299d275">How to Write Unit Tests for Combine Publishers in Swift Testing</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[How I Saved Over 80% on My AWS Hosting Bill with Hugo and S3]]></title>
            <link>https://levelup.gitconnected.com/how-i-saved-over-80-on-my-aws-hosting-bill-with-hugo-and-s3-17dc8b444e16?source=rss-7dd3527490eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/17dc8b444e16</guid>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[cost-optimisation]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[hugo]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Will Lumley]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 23:22:35 GMT</pubDate>
            <atom:updated>2024-10-21T23:22:35.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ha0hU9_UBLB-JwMHAnfqqg.jpeg" /><figcaption>Sora Shimazaki, <a href="https://www.pexels.com/photo/online-shopping-5935739">https://www.pexels.com/photo/online-shopping-5935739</a></figcaption></figure><p>When I first started hosting my website, I went the full stack route — spun up an EC2 instance, installed Linux, configured MySQL, and set up PHP. It felt like a rite of passage as a developer, and I firmly believe it’s something every dev should experience at least once. It’s not just about building a website — it’s about learning the inner workings of Apache, managing SSL certificates, and getting up close and personal with the command line.</p><p>However, there were a few small issues: it was costing me $25/month, it was cumbersome, and it was slow due to the small EC2 instance size. After a few months, I started wondering if I could host my website more cost-effectively. Spoiler alert: I could.</p><p>Today, I’m paying around $4 AUD / month, and my site runs faster, with automatic SSL, and I barely touch it after setup. Let me show you how I did it.</p><h4><strong>Why EC2 Isn’t Always the Best Option</strong></h4><p>Running an EC2 instance with Linux, MySQL, and PHP might sound simple, but it gets expensive fast. Between the instance cost, EBS storage, and data transfer fees, it adds up. Don’t get me wrong — setting up a website this way gives you a deep understanding of server management, and you’ll learn invaluable skills for your career. But in reality, for a lot of static websites, it’s overkill.</p><h4><strong>Enter Hugo, AWS S3, and CloudFront</strong></h4><p>After some research, I found a much cheaper and simpler solution: Hugo + S3 + CloudFront. This setup allows you to host a fast, secure, and scalable website with minimal costs and maintenance.</p><p>Here’s a breakdown of how you can set it up.</p><h3><strong>Build Your Site with Hugo</strong></h3><p>First of all, what is Hugo? Hugo is a fast and flexible static site generator that allows you to build websites using simple Markdown files, without the need for databases or complex server-side setups. It’s popular for its ease of use, wide range of themes, and ability to generate lightning-fast websites with minimal effort.</p><p>If you’ve never used Hugo before, the learning curve is pretty gentle, and there are heaps of themes to choose from. Feel free to explore the Hugo theme gallery.</p><p>You can read more about Hugo at their <a href="https://gohugo.io/">website</a>.</p><p>Going forward, I’m going to pretend that we’re making a website at the domain/URL my-awesome-site.com. So whenever you see my-awesome-site.com, just insert your own domain/URL.</p><p>To get started:</p><p>1. Install Hugo (you can find the installation steps on Hugo’s website).</p><p>2. Create a new Hugo site:</p><pre>hugo new site my-awesome-site</pre><p>3. Pick a theme and add your content in Markdown.</p><p>To run your hugo website locally and see what it looks like, run:</p><pre>hugo serve</pre><p>You will receive a URL in the command line (usually <a href="http://localhost:1313/)">http://localhost:1313/)</a> that you can navigate to in your browser to see a live preview of your website.</p><h3><strong>Set Up AWS S3 for Hosting</strong></h3><p>Your generated website will be in the /public directory of your repository. Now all we need to do is to host that content in the internet. Enter S3.</p><p>Here’s the process:</p><p>1. In AWS, create an S3 bucket with a name that matches your domain or desired URL (e.g., my-awesome-site.com). Make sure the bucket is set for public read access (you’ll configure this through bucket policies).</p><p>2. Once created, go to the “Properties” tab of your bucket and scroll down to “Static website hosting”. Select the “Edit” button. Here you will want to:</p><ul><li>set “Static website hosting” to “Enable”</li><li>set “Hosting type” to “Host a static website”</li><li>set the “Index document” to “index.html”</li></ul><p>3. Now navigate to the “Permissions” tab. “Block <em>all</em> public access” should be set to “off”.</p><p>4. Copy &amp; paste this into the “Bucket policy” input:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;PublicReadGetObject&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::my-awesome-site.com/*&quot;<br>        }<br>    ]<br>}</pre><p>5. Now you will also create another bucket, that will match your desired domain or URL, but with “www.” prepended to it (e.g., <a href="http://www.my-awesome-site.com)./">www.my-awesome-site.com).</a> The purpose of this bucket will be to redirect users who type in <a href="http://www.my-awesome-site.com/">www.my-awesome-site.com</a> to my-awesome-site.com.</p><p>6. Once created, go to the “Properties” tab of your bucket and scroll down to “Static website hosting”. Select the “Edit” button. Here you will want to:</p><ul><li>set “Static website hosting” to “Disable”</li><li>set “Hosting type” to “Redirect requests for an object”</li><li>set the “Host name” to “my-awesome-site.com”</li><li>set the “Protocol” to “https”</li></ul><p>7. Upload the contents of your public folder into your S3 bucket.</p><p>At this point, you could technically serve your website directly from S3. But it would be from the S3 domain (e.g. <a href="http://my-awesome-site.s3-website-ap-southeast-2.amazonaws.com),/">http://my-awesome-site.s3-website-ap-southeast-2.amazonaws.com),</a> would not support HTTPS protocol, and would have slower load times than we can get otherwise. To take take things a step further, we’ll integrate CloudFront. This will give us faster delivery of the website, automatic SSL support, and HTTPS redirect.</p><h3><strong>Configure CloudFront for Speed and SSL</strong></h3><p>CloudFront is AWS’s CDN service, and it’s perfect for distributing your content globally, reducing load times by serving your site from edge locations around the world.</p><p>To set it up:</p><p>1. Create a CloudFront distribution.</p><p>2. Select the “Origin domain” textfield. You should see your AWS S3 buckets drop down. Select the my-awesome-site.com bucket (<em>not</em> the <a href="http://www.my-awesome-site.com/">www.my-awesome-site.com</a> bucket).</p><p>3. Leave the “Origin path” blank.</p><p>4. Put in a name that you deem appropriate.</p><p>5. For “Viewer protocol policy”, select “Redirect HTTP to HTTPS”.</p><p>For now, leave the rest of the configurations as their default value and create your distribution.</p><p>Once your distribution is spun up, select it’s ID from your list of distributions to view it’s details. Now you’ll want to:</p><p>1. Scroll down to “Settings” and select “Edit”. Under the “Alternate domain name (CNAME) — optional” you’ll want to add two items.</p><p>2. Add “my-awesome-site.com”.</p><p>3. Add “www.my-awesome-site.com&quot;.</p><p>4. Under “Custom SSL certificate — optional” you can select “Request certificate”. This will take you to ACM and walk you through the steps of creating a certificate. Once it’s created, select that SSL certificate.</p><p>5. Under “Default root object — optional”, input “index.html”.</p><p>6. Save the settings.</p><h4><strong>Configure www. Redirect in CloudFront</strong></h4><p>Okay so now we’ll be configuring our www. redirect within CloudFront. This will ensure that when we go to <a href="http://www.my-awesome-site.com,/">www.my-awesome-site.com,</a> there will be an automatic redirect within the CloudFront layer that takes the user my-awesome-site.com.</p><p>Within CloudFront, you want to go to the “Functions” section. This is found on the left-hand side of the screen, behind a hamburger menu. Here we are going to write a small javascript script that will pick-up any requests that have the “www.” prepended to the domain, and redirect them to our site without the “www.”. Click on “Create function” to get started, and then follow the steps below:</p><p>1. Name the function something appropriate.</p><p>2. Select the latest version of cloudfront-js.</p><p>3. Copy and paste the code below:</p><pre>function handler(event) {<br>    var request = event.request;<br>    var headers = request.headers;<br>    var host = headers.host.value;<br><br>    // Check if the host is the naked domain<br>    if (host === &#39;www.my-awesome-site.com&#39;) {<br>        return {<br>            statusCode: 301,<br>            statusDescription: &#39;Moved Permanently&#39;,<br>            headers: {<br>                &quot;location&quot;: {<br>                    &quot;value&quot;: &quot;https://my-awesome-site.com&quot; + request.uri<br>                }<br>            }<br>        };<br>    }<br><br>    // If not the naked domain, just return the original request<br>    return request;<br>}</pre><p>The script is pretty straightforward. It picks up any requests with a “www” in the hostname, then redirects the user to a domain without the “www.”,and also ensures that the redirect follows the HTTPS protocol, along with the URI.</p><p>Now go back to your CloudFront Distribution, and select the “Behaviours” tab. Select the only behaviour that should be in your list of behaviours, and select the “Edit” button.</p><p>Scroll to the bottom of the page, to the “Function associations — optional” section. For the first row, select “CloudFront Functions” for the “Function type” field, and select your function name in the “Function ARN / Name” field.</p><p>Select the “Save changes” button.</p><h3><strong>Connecting to Route53</strong></h3><p>By now, we have our S3 bucket setup to hold our website content, and a CloudFront Distribution which caches the content in our S3 bucket, and stores a copy of it in servers all around the world. The final piece of this AWS configuration puzzle is to connect and configure our domain in Route53 to CloudFront.</p><p>In your Route53 domain configuration, you want to create a new record, specifically an A record. Follow these steps:</p><p>1. Leave the subdomain field blank.</p><p>2. For “Resource type”, select “A — Routes traffic to an IPV4 address and some AWS resources”.</p><p>3. Turn on the “Alias” switch.</p><p>4. For “Routes traffic to”, select “Alias to CloudFront distribution”.</p><p>5. For the field under “Routes traffic to”, select your CloudFront distribution ID. It should look something like “a1234abcdef.cloudfront.net.”</p><p>Now create another A record and repeat steps from 1 to 5, but for step 1 input “www” for the subdomain value.</p><p>Once that’s all configured — your AWS stack is setup. A user will make a request to my-awesome-site.com, which will get directed to Route53, which will point to your CloudFront distribution, which will have a cached version of the contents that exist in your S3 bucket.</p><p>I made a basic diagram to visualise what’s happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAbeJ_JMQTsVFgt8IdkL_A.png" /></figure><h3><strong>Automate with GitHub Actions</strong></h3><p>Now that your website is hosted on S3 and distributed via CloudFront, that’s everything done right? Not quite so! Currently, to update your website you would have to open up your Terminal, and in the root directory of your repo, type:</p><pre>hugo</pre><p>Hugo would then create a static website, and put it within the public directory of your repo. You would then have to copy and paste all the contents within the public directory and upload them to your my-awesome-site.com S3 bucket. Finally, you would have to prompt your CloudFront distribution to invalidate its current cache and pull in a new copy from S3. This is quite a time consuming and laborious process.</p><p>Let’s automate it!</p><p>Now I’m assuming you are hosting your repo on Github, as we’ll be leveraging Github Actions for the Continuous Distribution pipeline.</p><p>Here’s how I set it up:</p><p>1. Create a GitHub repository for your Hugo site.</p><p>2. Set up GitHub Actions for Continuous Deployment. With each push to main, you can trigger a pipeline that:</p><p>a. Builds your Hugo site</p><p>b. Uploads the content to your S3 bucket</p><p>c. Invalidates the CloudFront cache to ensure the latest content is served</p><p>Here’s an example of a basic GitHub Actions workflow that does just that:</p><pre>name: Build and Deploy<br><br>on:<br> push:<br>   branches: [ &quot;main&quot; ]<br><br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br><br>    # Checks out your repository<br>    - name: Checkout<br>      uses: actions/checkout@v2<br><br>    # Setup Hugo<br>    - name: Setup Hugo<br>      uses: peaceiris/actions-hugo@v2<br>      with:<br>        hugo-version: &#39;latest&#39; # specify the Hugo version you want<br><br>    # Build the Hugo site<br>    - name: Build<br>      run: hugo --minify<br><br>    # Deploys built website to S3<br>    - name: Deploy to S3<br>      run: hugo deploy --force --maxDeletes -1 --invalidateCDN<br>      env:<br>        AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>        AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}</pre><p>This pipeline does all the heavy lifting, ensuring that after each update, your site is deployed, and the cache is cleared. Now, instead of manually uploading files or fiddling with cache settings, the pipeline takes care of everything.</p><p>Hold on though, eagle-eyed readers would have noticed something. We are using secrets.AWS_ACCESS_KEY_ID and secrets.AWS_SECRET_ACCESS_KEY. What exactly are they?</p><p>These are AWS credentials that allow GitHub Actions to interact with your AWS account securely. Specifically:</p><ul><li>AWS_ACCESS_KEY_ID is the ID of an access key that grants programmatic access to your AWS account.</li><li>AWS_SECRET_ACCESS_KEY is the secret part of that access key, which acts as a password to authenticate your requests.</li></ul><p>By storing these in GitHub’s secrets, they are securely hidden from anyone browsing your code repository and ensure that only your GitHub Actions workflow can access them. To set these up, you’ll need to generate an access key in the AWS IAM console and then add them to your repository’s secrets under Settings &gt; Secrets in GitHub.</p><p>This setup lets GitHub Actions push your static site to your S3 bucket and interact with other AWS services without exposing sensitive information publicly.</p><p>In the next section I’ll go over how to create AWS credentials that you can use for the automation pipeline, and how to securely insert them into your Github repo.</p><h3><strong>Creating Secure AWS Credentials</strong></h3><p>Venture back into your AWS Dashboard, and go into the Identity and Access Management portal, or IAM. IAM is a service within AWS that helps you securely manage access to your AWS resources. It allows you to create and manage users, groups, and roles with specific permissions.</p><p>With IAM, you can control who has access to what resources and at what level. For example, you can create users who have permission to only upload files to an S3 bucket or manage CloudFront distributions. The key benefit is that it enables you to implement the principle of least privilege, giving only the necessary permissions to each user or service to perform its tasks, thus reducing the risk of accidental or malicious actions.</p><p>We are going to create two policies; one for invalidating your my-awesome-site.com CloudFront distribution cache, and one for read/write access to your my-awesome-site.com bucket.</p><h4><strong>Policies</strong></h4><p>Within IAM, navigate to the Policies section, and then select the “Create policy” button.</p><p>In the Policy Creation page, select the “JSON” toggle. Copy and paste the JSON below.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:ListBucket&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::my-awesome-site.com&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:DeleteObject&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::my-awesome-site.com/*&quot;<br>        }<br>    ]<br>}</pre><p>Select the “Next” button. Then give the policy a name, like “MyAwesomeSite_S3”.</p><p>Create another policy, using the JSON below.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;cloudfront:CreateInvalidation&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:cloudfront::750590170583:distribution/E2A67O8F89PMSR&quot;<br>        }<br>    ]<br>}</pre><p>Select the “Next” button. Then give the policy a name, like “MyAwesomeSite_CloudFront_Invalidation”.</p><h4><strong>Users</strong></h4><p>Now navigate to the “Users” section of IAM. Select the “Create user” button. Provide a username for this user, such as “myawesomesite_deployer”. Ensure the “Provide user acess to the AWS Management Console” checkbox is <em>not</em> selected.</p><p>Select the “Next” button.</p><p>For “Permissions options”, select “Attach policies directly”. In the list of permissions below, search for the names of the policies we created earlier. In our case, they are “MyAwesomeSite_S3”, and “MyAwesomeSite_CloudFront_Invalidation”.</p><p>Select the “Next” button, and then the “Create user” button.</p><h4><strong>Creating AWS Credentials</strong></h4><p>View the users profile within the IAM Users list. Within the “Summary” section, select the “Create access key” link. Select the “Command Line Interface (CLI)” for the “Use case”. Then select the “Create access key” button.</p><p>You will then be presented with an <em>Access key</em> and a <em>Secret access key</em>. Store these somewhere secure.</p><h4><strong>Storing the AWS Credentials in Github Actions</strong></h4><p>Open up your repo on Github, and navigate to the “Settings” tab. On the left-hand side menu, under the “Security” section, select “Secrets and variables”, and then “Actions”.</p><p>Under the “Secrets” tab, select “New repository secret”.</p><p>Put in “AWS_ACCESS_KEY_ID” for the name, and your access key for the value.</p><p>Do this once more, but put in “AWS_SECRET_ACCESS_KEY” for the name, and your secret key for the value.</p><h3><strong>Testing the New Ride!</strong></h3><p>Once everything is configured, it’s time to test the entire setup. Push your changes to the main branch of your GitHub repository, and you should see the GitHub Actions workflow kick off automatically.</p><p>Here’s what you’ll want to check during the process:</p><p>1. GitHub Actions Pipeline: Head over to the Actions tab in your repository and verify that your deployment pipeline runs without errors. You should see it checkout your code, build your Hugo site, upload the content to your S3 bucket, and invalidate your CloudFront cache.</p><p>2. S3 and CloudFront Setup: After the pipeline completes, check that your content has been successfully deployed to the S3 bucket and distributed via CloudFront. You can do this by visiting your domain (e.g., <a href="https://my-awesome-site.com)/">https://my-awesome-site.com)</a> in a browser. Make sure everything is loading correctly, including any CSS, images, and other assets.</p><p>3. SSL and Redirects: Test both the http:// and https:// versions of your site, as well as the www. and non-www. versions, to ensure they redirect correctly to the secure HTTPS version of your domain without the www. prefix. If you configured everything properly, CloudFront should automatically handle these redirects.</p><p>4. Performance: One of the big perks of this setup is the improved performance thanks to CloudFront’s CDN. You should see significant speed improvements due to CloudFront’s ability to cache content globally at its edge locations. For even deeper insights, you can use tools like Google PageSpeed Insights or GTmetrix to check the loading times and optimisations.</p><h3><strong>Enjoy the Savings, Speed, and Scalability</strong></h3><p>By moving from an EC2 instance with MySQL and PHP to this Hugo + S3 + CloudFront setup, I cut my costs down from $25 to $4/month. This includes the cost of the S3 bucket, CloudFront distribution, and small amounts of data transfer fees.</p><p>Not only am I saving money, but my site is faster, I don’t have to worry about server maintenance, and AWS automatically handles SSL for me.</p><p>Hosting a static website in 2024 doesn’t have to cost a fortune. Moving to Hugo, S3, and CloudFront has been a game-changer for me. It’s faster, more efficient, and much cheaper.</p><p>If you’re still hosting your blog on an EC2 instance, I recommend giving this setup a try. The time you invest in setting up Hugo and AWS will pay off quickly in terms of cost savings and the peace of mind that comes from a more maintainable solution.</p><p>And if you’re looking for more ways to optimise your setup or have any questions about this process, feel free to reach out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17dc8b444e16" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-i-saved-over-80-on-my-aws-hosting-bill-with-hugo-and-s3-17dc8b444e16">How I Saved Over 80% on My AWS Hosting Bill with Hugo and S3</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[Using a NavigationStack with MVVM and SwiftUI]]></title>
            <link>https://levelup.gitconnected.com/using-a-navigationstack-with-mvvm-and-swiftui-36617c9f9147?source=rss-7dd3527490eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/36617c9f9147</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Will Lumley]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 06:47:13 GMT</pubDate>
            <atom:updated>2024-04-30T17:45:49.760Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hxxxrt_PaNyFg12MwS6-mQ.jpeg" /><figcaption>Jamie Street, <a href="https://unsplash.com/photos/person-holding-compass-facing-towards-green-pine-trees-_94HLr_QXo8?utm_content=creditShareLink&amp;utm_medium=referral&amp;utm_source=unsplash">https://unsplash.com/photos/person-holding-compass-facing-towards-green-pine-trees-_94HLr_QXo8?utm_content=creditShareLink&amp;utm_medium=referral&amp;utm_source=unsplash</a></figcaption></figure><p>In the ever-evolving landscape of iOS development, SwiftUI has marked a revolution with its declarative syntax and promise of simplifying complex UI implementations. As developers, we constantly seek architectures that not only streamline development but also enhance maintainability and testability. Among these, the Model-View-ViewModel (MVVM) pattern has emerged as a favorite for many, including myself, for its clear separation of concerns and ease of integration with SwiftUI. However, even the most seasoned developers can encounter hurdles that challenge their preferred methodologies.</p><p>I was working on my first production-level SwiftUI application, which uses MVVM, when I first encountered what I initially assumed to be a quickly solved problem.</p><p>Despite SwiftUI’s graceful declarative syntax and promises of straightforward UI development, I couldn’t find an obvious solution to this problem:</p><p>How in the hell do I incorporate a NavigationStack into SwiftUI and keep my ViewModel and View layers seperate and clean?</p><p>After doing some research and not being entirely satisfied with the potential solutions that people had posted, I decided to put my big boy boots on and try it myself.</p><p>Now I’ll give you fair warning — I’m not claiming this is the best solution nor the perfect solution — however I found it to be exactly what I needed. Nothing crazy complicated nor over the top, and allows for navigating between views in a NavigationStack — all while keeping View and ViewModel seperate.</p><p>I recommend downloading the finished project, linked below, and read through the code with me.</p><p><a href="https://github.com/will-lumley/swiftui-navigation-example">https://github.com/will-lumley/swiftui-navigation-example</a></p><h3><strong>Let’s meet the crew</strong></h3><p>RootViewModel</p><p>You can think of the RootViewModel as the ViewModel for the NavigationStack itself. Or, to think in UIKit terms for a moment, as the ViewModel for the UINavigationController.</p><p>RootView</p><p>This is the View that will contain the NavigationStack, and for all intents and purposes, <em>be</em> the NavigationStack. To think in UIKit terms for another moment, this would be the UINavigationController.</p><p>NavigationCoordinator</p><p>This is the protocol that RootViewModel must conform to, and is what essentially turns our RootViewModel from any ViewModel to one that can handle navigation events, and in turn one that can communicate with the NavigationStack on the View layer.</p><p>FirstContentView &amp; FirstContentViewModel<br>This is our first example View &amp; ViewModel in our app, that represent the first View &amp; ViewModel you would have in your application.</p><p>SecondContentView &amp; SecondContentViewModel</p><p>This is our second example View &amp; ViewModel in our app, that are pushed onto the NavigationStack from the FirstContentView / FirstContentViewModel.</p><p>ThirdContentView &amp; ThirdContentViewModel</p><p>This is our third example View &amp; ViewModel in our app, that are pushed onto the NavigationStack from the SecondContentView / SecondContentViewModel.</p><h3><strong>NavigationCoordinator</strong></h3><p>Our NavigationCoordinator is crucial in separating the View &amp; ViewModel layers. NavigationCoordinator allows us to abstract navigation actions such as pushing and popping views, keeping our ViewModel away from the intricacies of SwiftUI’s navigation system.</p><p>It’s extremely simple, as you can see below.</p><pre>public protocol NavigationCoordinator {<br><br>    func push(_ path: any Hashable)<br>    func popLast()<br><br>}</pre><h3><strong>RootViewModel</strong></h3><p>RootViewModel is where the magic happens. I’ve pasted its contents down below. Have a browse through it, and I’ll catch up with you down below and we can go over it together.</p><pre>public class RootViewModel: ObservableObject, Identifiable {<br><br>    // MARK: - Types<br><br>    public enum Path: Hashable {<br>        case first(FirstContentViewModel)<br>        case second(SecondContentViewModel)<br>        case third(ThirdContentViewModel)<br>    }<br><br>    // MARK: - Properties<br><br>    public var id = UUID()<br><br>    /// The object that handles our navigation stack<br>    @Published public var paths = NavigationPath()<br><br>    /// The ViewModel that represents our first view in the navigation stack<br>    public lazy var firstContentViewModel: FirstContentViewModel = {<br>        .init(navigator: self, text: &quot;First!&quot;)<br>    }()<br><br>}<br><br>// MARK: - NavigationCoordinator<br><br>extension RootViewModel: NavigationCoordinator {<br><br>    public func push(_ path: any Hashable) {<br>        DispatchQueue.main.async { [weak self] in<br>            self?.paths.append(path)<br>        }<br>    }<br><br>    public func popLast() {<br>        DispatchQueue.main.async { [weak self] in<br>            self?.paths.removeLast()<br>        }<br>    }<br><br>}</pre><p>Great. Now we’ll go through RootViewModel piece by piece.</p><p>Let’s start off with the Path type.</p><pre>    public enum Path: Hashable {<br>        case first(FirstContentViewModel)<br>        case second(SecondContentViewModel)<br>        case third(ThirdContentViewModel)<br>    }</pre><p>This enum represents every possible ViewModel that can be pushed onto the NavigationStack.</p><p>In this example, we have three ViewModel’s, and each one is listed here and contained within an associated value.</p><p>Note that Path conforms to Hashable, which means that each of your ViewModel’s must conform toHashable. Don’t worry though, this is simple to implement.</p><p>Now we have our paths property:</p><pre>@Published public var paths = NavigationPath()</pre><p>The paths property is the object that we will store our Path.first() or Path.second() or Path.third(), etc, when pushed.</p><p>We use the @Published property wrapper so that whenever a value is added or taken away from paths, SwiftUI can receive the updates automatically.</p><p>Keen eyed readers would have spotted something wrong with this though.</p><p>Can you spot it?</p><p>That’s right! NavigationPath belongs to SwiftUI, and importing/using SwiftUI within our ViewModel layer is a no-no. Alas, I could not figure out a way to get this to work, cleanly, without using this.</p><p>So while not great — all things considered — it’s not the end of the world.</p><p>Onto the next property, this lazy-loaded variable:</p><pre>    public lazy var firstContentViewModel: FirstContentViewModel = {<br>        .init(navigator: self, text: &quot;First!&quot;)<br>    }()</pre><p>This property, firstContentViewModel, is our first ViewModel in our NavigationStack. We store it as a property of our RootViewModel so that we can load the ViewModel as soon as RootViewModel loads up.</p><p>You’ll notice how FirstContentViewModel has a navigator parameter in its instance. Each ViewModel in our NavigationStack will have this property and have it passed to it through its initialiser.</p><p>It is needed as it is how it pushes and pops views in the navigation flow. As for how it does this, we’ll get into that later on.</p><p>Let’s now hvae a look at RootViewModel’s conformance to NavigationCoordinator:</p><pre>extension RootViewModel: NavigationCoordinator {<br><br>    public func push(_ path: any Hashable) {<br>        DispatchQueue.main.async { [weak self] in<br>            self?.paths.append(path)<br>        }<br>    }<br><br>    public func popLast() {<br>        DispatchQueue.main.async { [weak self] in<br>            self?.paths.removeLast()<br>        }<br>    }<br><br>}</pre><p>These functions, push(_ path:) and popLast(), will be called by ViewModel’s in the navigation flow.</p><p>In regards to push(_ path:), the path parameter will be a RootViewModel.Path type, with it’s type erased to any Hashable.</p><p>We ensure that any changes to the paths variable is done on the main thread with DispatchQueue.main.async, as changes to paths propagate to the View layer, which of course must be performed on the main thread.</p><p>popLast() simply removes the last item from the paths “array”.</p><p>Just to reiterate — any changes made to the paths array will update the navigation flow. So while we now have the foundation for us to push ViewModels to our paths, how do we connect a ViewModel being pushed onto the navigation flow with a View being pushed onto the NavigationStack?</p><p>Enter RootView .</p><h3><strong>RootView</strong></h3><p>RootView listens to any changes made to the RootViewModel and will either connect the ViewModel pushed to it’s View being pushed, and remove (or “pop”) any View from the NavigationStack once it’s ViewModel is removed.</p><p>Let’s take a look at RootView now:</p><pre>struct RootView: View {<br><br>    // MARK: - Properties<br><br>    @StateObject var viewModel: RootViewModel<br><br>    // MARK: - View<br><br>    var body: some View {<br>        <br>        NavigationStack(path: $viewModel.paths) {<br>            FirstContentView(viewModel: viewModel.firstContentViewModel)<br>                .navigationDestination(for: RootViewModel.Path.self) { path in<br>                    switch path {<br>                    case .first(let viewModel):<br>                        FirstContentView(viewModel: viewModel)<br>                    case .second(let viewModel):<br>                        SecondContentView(viewModel: viewModel)<br>                    case .third(let viewModel):<br>                        ThirdContentView(viewModel: viewModel)<br>                    }<br>                }<br>        }<br><br>    }<br>}</pre><p>The NavigationStack encapsulates all views within RootView with the SwiftUI equivalent of UINavigationController.</p><p>We pass in our ViewModels variable of paths (and use $ to make it Binding). This enables two things:</p><p>1. The NavigationStack instance can now listen to any updates from the paths property, and when a change is made push (or pop) a View accordingly. A push operation will map the ViewModel to the View in the .navigationDestination modifier.</p><p>2. The NavigationStack can itself modify the paths property. This would happen when a user selects the built-in Navigation back button, and then the latest ViewModel would need to be popped.</p><p>As the first view in our NavigationStack is FirstContentView, we instantiate it within our NavigationStack, with the lazy-loaded variable within RootViewModel we wrote earlier.</p><p>Our .navigationDestination modifier listens to any updates in paths that are of type RootViewModel.Path. We can then run a switch statement and determine the path type.</p><p>Here we can then get the Path type, which will give us our ViewModel. This is where the connection and link between ViewModel and View happens. We will then declare a View, depending on the ViewModel. The View that is declared is the View that will be pushed onto the NavigationStack.</p><h3><strong>FirstContentView</strong></h3><p>Our FirstContentView is pretty straightforward, so I won’t spend time going over it. It’s also very similar to SecondContentView and ThirdContentView, so I won’t bother going over those either.</p><pre>struct FirstContentView: View {<br><br>    // MARK: - Properties<br><br>    @StateObject var viewModel: FirstContentViewModel<br><br>    // MARK: - View<br><br>    var body: some View {<br>        VStack {<br>            Text(viewModel.text)<br>                .font(.headline)<br>                .padding()<br><br>            Spacer()<br><br>            Button(&quot;Next Screen&quot;) {<br>                viewModel.nextButtonSelected()<br>            }<br>            .buttonStyle(BorderedButtonStyle())<br>            .padding()<br>        }<br>        .navigationTitle(&quot;First View&quot;)<br>    }<br>}<br><br>#Preview {<br>    FirstContentView(<br>        viewModel: .init(<br>            navigator: MockNavigationCoordinator(),<br>            text: &quot;Test&quot;<br>        )<br>    )<br>}</pre><h3><strong>FirstContentViewModel</strong></h3><p>Let’s now take a good look at FirstContentViewModel. This will demonstrate how to push and pop ViewModels (and by extension, Views) onto our navigation flow.</p><pre>public final class FirstContentViewModel: ObservableObject {<br><br>    // MARK: - Properties<br><br>    @Published public var text: String<br><br>    private let navigator: NavigationCoordinator<br><br>    // MARK: - Lifecycle<br><br>    init(navigator: NavigationCoordinator, text: String) {<br>        self.navigator = navigator<br>        self.text = text<br>    }<br><br>}<br><br>// MARK: - Public<br><br>public extension FirstContentViewModel {<br><br>    func nextButtonSelected() {<br>        self.navigator.push(<br>            RootViewModel.Path.second(<br>                SecondContentViewModel(navigator: navigator, text: &quot;Second!&quot;)<br>            )<br>        )<br>    }<br><br>}<br><br>// MARK: - Hashable<br><br>extension FirstContentViewModel: Hashable {<br><br>    public static func == (lhs: FirstContentViewModel, rhs: FirstContentViewModel) -&gt; Bool {<br>        return lhs.text == rhs.text<br>    }<br><br>    public func hash(into hasher: inout Hasher) {<br>        hasher.combine(self.text)<br>    }<br>    <br>    <br>}</pre><p>The text property is just a simple example of a property that might exist on the ViewModel that you pass onto the View. You can ignore it.</p><p>The navigator property is much more important.</p><pre>private let navigator: NavigationCoordinator</pre><p>This is the property our ViewModel will use to manipulate the navigation flow.</p><pre>func nextButtonSelected() {<br>        self.navigator.push(<br>            RootViewModel.Path.second(<br>                SecondContentViewModel(navigator: navigator, text: &quot;Second!&quot;)<br>            )<br>        )<br>    }</pre><p>As you can see in our nextButtonSelected() function, our ViewModel can push a ViewModel onto the navigation flow.</p><p>When you test this code, you’ll be able to see that pushing SecondContentViewModel onto our navigator will push the SecondContentView onto our NavigationStack, and will configure that SecondContentView with our SecondContentViewModel that we created &amp; configured.</p><p>Popping a View/ViewModel doesn’t exist in FirstContentView/FirstContentViewModel as it’s our inital View/ViewModel, so let’s take a look at how deeper ViewModel’s perform it.</p><pre>func backButtonSelected() {<br>    self.navigator.popLast()<br>}</pre><p>How easy is that?</p><h3><strong>Unit Tests, oh my!</strong></h3><p>The standout feature of MVVM is its ability to facilitate the testing of both business logic and view logic independently, eliminating the need to configure views within a unit test — which is notoriously difficult.</p><p>So now that we have all this setup, let’s have a look at how we can test our navigation.</p><p>As NavigationCoordinator is a protocol, we can create a separate NavigationCoordinator that will listen out for pushes and pops, but rather than binding them to a View’s NavigationStack, we will broadcast these events using closures.</p><h3><strong>MockNavigationCoordinator</strong></h3><pre>class MockNavigationCoordinator: NavigationCoordinator {<br><br>    // MARK: - Types<br><br>    typealias OnPush = (_ path: any Hashable) -&gt; Void<br>    typealias OnPop = () -&gt; Void<br><br>    let onPush: OnPush?<br>    let onPop: OnPop?<br><br>    // MARK: - Lifecycle<br><br>    init() {<br>        self.onPush = nil<br>        self.onPop = nil<br>    }<br><br>    init(onPush: @escaping OnPush, onPop: @escaping OnPop) {<br>        self.onPush = onPush<br>        self.onPop = onPop<br>    }<br><br>    // MARK: - NavigationCoordinator<br><br>    func push(_ path: any Hashable) {<br>        onPush?(path)<br>    }<br><br>    func popLast() {<br>        onPop?()<br>    }<br><br>}</pre><p>Now we can write our unit test:</p><pre>final class FirstContentViewModelTests: XCTestCase {<br><br>    func testNavigation() throws {<br>        var pushed: (any Hashable)?<br>        var popped = false<br><br>        // Create our MockNavigationCoordinator so we can listen to push/pop events<br>        let navigator = MockNavigationCoordinator(<br>            onPush: {<br>                // Record what path was just pushed<br>                pushed = $0<br>            },<br>            onPop: {<br>                // Record that we just popped<br>                popped = true<br>            }<br>        )<br><br>        // Setup our TestSubject<br>        let testSubject = FirstContentViewModel(navigator: navigator, text: &quot;test text&quot;)<br><br>        // We&#39;ll do some basic house cleaning<br>        XCTAssertEqual(testSubject.text, &quot;test text&quot;)<br><br>        // Tell our FirstContentViewModel to select our next button<br>        testSubject.nextButtonSelected()<br><br>        // A path should just now be pushed onto our NavigationCoordinator<br>        let pushedPath = try XCTUnwrap(pushed as? RootViewModel.Path)<br><br>        // And that path should contain a SecondContentViewModel<br>        guard case .second(let secondViewModel) = pushedPath else {<br>            XCTFail(&quot;Incorrect type returned&quot;)<br>            return<br>        }<br><br>        // The SecondContentViewModel should contain the correct properties<br>        XCTAssertEqual(secondViewModel.text, &quot;Second!&quot;)<br><br>        // If we go back with our SecondContentViewModel...<br>        secondViewModel.backButtonSelected()<br><br>        // ...we should have that recorded<br>        XCTAssertTrue(popped)<br>    }<br><br>}</pre><p>This approach allows for precise tracking and verification of navigation behaviour. For instance, when the FirstContentViewModel triggers a navigation to the SecondContentViewModel, we not only verify that a navigation action occurred but also validate the type of view model that was navigated to, ensuring it aligns with expected behaviour. This is achieved by capturing the navigation action’s target and evaluating its properties, which in this case, includes verifying the text property of the SecondContentViewModel.</p><p>Moreover, the test suite goes a step further by simulating user interaction that leads to a navigation action (e.g., tapping a ‘next’ button), and subsequently, confirming that the correct navigation path is taken. This includes asserting the transition from the FirstContentViewModel to the SecondContentViewModel and then testing the reverse navigation (pop action) back to the original state.</p><h3><strong>Conclusion</strong></h3><p>Navigating SwiftUI with MVVM can feel daunting, but the solution we’ve explored — leveraging NavigationStack, RootViewModel, and the NavigationCoordinator protocol — demonstrates that it’s entirely possible to maintain clean architecture while embracing SwiftUI’s modern UI paradigms. This approach not only streamlines navigation but also ensures our code remains flexible and maintainable.</p><p>However, the tech landscape is always evolving, and today’s solutions may pave the way for more refined approaches tomorrow. This journey isn’t just about overcoming a challenge; it’s about opening a dialogue on continuous improvement and innovation within our community.</p><p>I invite you to experiment with this framework, adapt it to your needs, and share your insights. Have you faced similar hurdles? What strategies worked for you?</p><p>Thank you for reading, and here’s to the next challenge we tackle together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36617c9f9147" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/using-a-navigationstack-with-mvvm-and-swiftui-36617c9f9147">Using a NavigationStack with MVVM and SwiftUI</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[A Pure Swift Library To Find Favicons Used by Any Website]]></title>
            <link>https://medium.com/better-programming/finding-favicons-a-brief-explanation-dbc484c144bb?source=rss-7dd3527490eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbc484c144bb</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[favicon]]></category>
            <dc:creator><![CDATA[Will Lumley]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 03:49:23 GMT</pubDate>
            <atom:updated>2023-07-21T16:19:30.403Z</atom:updated>
            <content:encoded><![CDATA[<h4>Designed for iOS and macOS applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*UFNT4y9MDjqkCLLP3BwrXQ.png" /><figcaption>github.com/will-lumley/FaviconFinder</figcaption></figure><p>Some time ago, I was working on an iOS application that required me to fetch and display the favicon of a given URL.</p><p>Easy right? Well, not so much.</p><p>About 15 to 20 years ago, you’d be fine to set up a simple HTTP GET request at the server&#39;s root with favicon.ico appended to it. So getting the favicon of the URL https://example.com would be as simple as an HTTP GET request to https://example.com/ico. You could get the image data from that request, ensure it’s displayed to the user, and then call it a day. Dust your hands off and be thankful for the easy retrieval.</p><p>Fast forward to the present day — I noticed that when using this method, many URLs weren’t having their favicon found.</p><pre> let urlResponse = try await URLSession.shared.data(from: url)<br> let imageData = urlResponse.0<br> guard let image = UIImage(data: imageData) else {<br>     return<br> }</pre><p>Strange, I thought. After investigating, some of the URLs were returning HTTP 401s, meaning that there was nothing at https://example.com/favicon.ico for me to find. After taking to Google, a few things became apparent. Firstly, the favicon may not be at the server root. It may be somewhere like https://example.com/images/images/favicon.ico.</p><p>Secondly, it may have a different file extension. As the file types range from PNG to SVG, it really is a mixed bag of possibilities. Thirdly, the filename of the image doesn’t have to be favicon, it could be anything the developer sees appropriate.</p><p>So, if all these possibilities exist, how can we find the favicon? The answer lies in the header section of the HTML page found at our URL. Below is a basic example of how favicons can be declared in the HTML.</p><pre>&lt;link rel=”shortcut icon” href=”favicon.ico”&gt;<br>&lt;link rel=”icon” type=”image/png” href=”/images/favicon-108x108.png”&gt;</pre><p>Hold on, there are more than one favicons listed here?</p><p>Nowadays, it’s quite common for websites to declare several favicons. This is to allow a website to have favicons with a wide range of image sizes and image types, as different platforms will have different preferences for what favicons they want — and the developer of the website is offering a wide array of favicons so the platform can fetch the favicon they deem most appropriate.</p><p>Now we know where to find the favicon declarations in HTML. However, implementing that in our iOS application is a little more difficult.</p><p>First, we must find an HTML parser to fetch the HTML page and iterate through its tags. I found that scinfu’s SwiftSoup repository works really well, and it works well with Cocoapods, Carthage, and SPM, so you’ll be able to integrate it into your project regardless of what dependency manager you’re using.</p><p><a href="https://github.com/scinfu/SwiftSoup">https://github.com/scinfu/SwiftSoup</a></p><p>The code below demonstrates how to use SwiftSoup to fetch the favicon URL:</p><pre>var htmlOpt: Document?<br>do {<br>   htmlOpt = try SwiftSoup.parse(htmlStr)<br>}<br>catch let error {<br>    print(&quot;Could NOT parse HTML due to error: \(error). HTML: \(htmlStr)&quot;)<br>    return nil<br>}<br> <br>guard let html = htmlOpt else {<br>    print(&quot;Could NOT parse HTML from string: \(htmlStr)&quot;)<br>    return nil<br>}<br> <br>guard let head = html.head() else {<br>   print(&quot;Could NOT parse HTML head from string: \(htmlStr)&quot;)<br>   return nil<br>}<br>var allLinks = Elements()<br>do {<br>    allLinks = try head.select(&quot;link&quot;)<br>}<br>catch let error {<br>    print(&quot;Could NOT parse HTML due to error: \(error). HTML: \(htmlStr)&quot;)<br>    return nil<br>}<br>let faviconTypes = [<br>    &quot;apple-touch-icon&quot;,<br>    &quot;apple-touch-icon-precomposed&quot;,<br>    &quot;shortcut icon&quot;,<br>    &quot;icon&quot;<br>]<br>var favicons = [String]()<br> <br>// Iterate over every &#39;link&#39; tag that&#39;s in the head document, and collect them<br>for element in allLinks {<br>    do {<br>        let rel = try element.attr(&quot;rel&quot;)<br>        let href = try element.attr(&quot;href&quot;)<br>        let sizes = try element.attr(&quot;sizes&quot;)<br>        // If this is an icon that we deem might be a favicon, add it to our array<br>        if faviconTypes.contains(rel) {<br>            favicons.append(rel)<br>        }<br>    }<br>    catch let error {<br>        self.logger?.print(&quot;Could NOT parse HTML due to error: \(error). HTML: \(htmlStr)&quot;)<br>        continue<br>    }<br> }</pre><p>Great, now we have written some basic logic that allows us to extract the URLs for the favicons from a website at a given URL. However, this is far from production-ready. There are other ways for developers to declare their favicons — such as in a web-application manifest JSON file — the file itself is declared in the HTML header, or in a similar fashion, there is Microsoft’s browser configuration XML file.</p><p>We also need to implement functionality that allows us to try one method of favicon searching (i.e., querying the HTML header for declarations), and then if that fails to fallback to another method (i.e., searching for filename).</p><p>There are other functionalities that would be nice to have, such as checking the root domain of a URL if a subdomain fails (i.e., querying https://example.com if https://subdomain.example.comfails). There is also checking for something called a meta refresh redirect. This is a client-side redirect (unlike HTTP 301, which is a server-side redirect) — where we have to manually check the HTML header tag for the meta refresh redirect and then spawn a new URLRequest with the URL contained within the HTML header tag.</p><p>If this all sounds like a giant headache, I have you covered. I have written a pure Swift iOS and macOS open source repository that handles all of this for you. It’s called FaviconFinder, and you can find it here:</p><p><a href="https://github.com/will-lumley/FaviconFinder">https://github.com/will-lumley/FaviconFinder</a></p><p>With FaviconFinder, all you have to call is</p><pre>let url = URL(string: “https://example.com&quot;)!<br>let favicon = try await FaviconFinder(url: url).downloadFavicon()</pre><p>If you want to have a fine-tuned control of what type of favicon you’re after, you can use FaviconFinder as follows:</p><pre>let favicon = try await FaviconFinder(<br>    url: url, <br>    preferredType: .html, <br>    preferences: [<br>        .html: FaviconType.appleTouchIcon.rawValue,<br>        .ico: “favicon.ico”,<br>        .webApplicationManifestFile: FaviconType.launcherIcon4x.rawValue<br>    ]<br> ).downloadFavicon()</pre><p>This allows you to control what type of download type FaviconFinder will use first and what subtype to look for when iterating through each download type. For the HTML download type, this allows you to prioritise different “rel” types. For the file.ico type, this allows you to choose the filename.</p><p>Suppose your desired download type doesn’t exist for your URL (i.e., you requested the favicon that exists as a file, but there’s no file). In that case, FaviconFinder will automatically try all other methods of favicon storage for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbc484c144bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/finding-favicons-a-brief-explanation-dbc484c144bb">A Pure Swift Library To Find Favicons Used by Any Website</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>