<?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 Abdul Sami Sultan on Medium]]></title>
        <description><![CDATA[Stories by Abdul Sami Sultan on Medium]]></description>
        <link>https://medium.com/@abdulsami923?source=rss-2156f8dda5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TQeeV-7I34-3B5JFsH6DsA.png</url>
            <title>Stories by Abdul Sami Sultan on Medium</title>
            <link>https://medium.com/@abdulsami923?source=rss-2156f8dda5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:41:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdulsami923/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From ESP32 to an iOS App: Understanding IoT with MicroPython and MQTT]]></title>
            <link>https://medium.com/@abdulsami923/from-esp32-to-an-ios-app-understanding-iot-with-micropython-and-mqtt-f62e2f23611c?source=rss-2156f8dda5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f62e2f23611c</guid>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[internet-of-things]]></category>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[micropython]]></category>
            <dc:creator><![CDATA[Abdul Sami Sultan]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 20:58:46 GMT</pubDate>
            <atom:updated>2026-11-25T20:58:46.476Z</atom:updated>
            <content:encoded><![CDATA[<p>Use a simulated weather station to follow a sensor reading from GPIO 15 to a JSON payload an iPhone can understand.</p><p>Move the temperature slider in a simulator. A new JSON message appears in the console. Change the humidity and another message is published. Leave both values alone and the program prints “No change.”</p><p>For an iOS developer exploring IoT, this is a useful place to start. You can see where the readings originate and what crosses the network before building a screen around them.</p><p>This walkthrough uses Uri Shaked’s MicroPython weather-station example for Wokwi. The ESP32 reads a simulated DHT22 and publishes changes through MQTT. We’ll explain that flow, then map its payload into a Swift model. The screenshot below captures the sensor settings and outgoing messages. <a href="https://wokwi.com/projects/322577683855704658">Original Wokwi project</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlqH5pvSbnf0tHsi9IWxcg.jpeg" /><figcaption>The supplied simulation screenshot. The final published payload contains a temperature of −3°C and relative humidity of 52%.</figcaption></figure><h3>Follow one reading through the system</h3><pre>DHT22 → ESP32 → MQTT broker → subscriber<br>                              ↳ future iOS dashboard</pre><p>The DHT22 supplies temperature and relative humidity. The ESP32 runs MicroPython, reads the sensor, and publishes JSON to the topic wokwi-weather. A subscriber connected to the same broker receives matching messages.</p><p>The publisher doesn’t need to know how many dashboards are listening. A terminal client and an iPhone app can subscribe independently. MQTT’s broker routes messages by topic. The iOS connection described later is the next integration step; the supplied screenshot demonstrates the simulated firmware’s console output.</p><h3>Connect the simulated sensor</h3><p>The screenshot uses three DHT22 connections.</p><ul><li><strong>VCC</strong> connects to the ESP32’s 3.3V supply.</li><li><strong>SDA/data</strong> connects to GPIO 15.</li><li><strong>GND</strong> connects to ground. The NC pin is unused.</li></ul><p>That data connection is represented in the program by dht.DHT22(Pin(15)). In Wokwi, click the DHT22 to change its simulated temperature and humidity. These are simulator inputs rather than measurements of your room. Wokwi documents the sensor&#39;s pins and controls. <a href="https://docs.wokwi.com/parts/wokwi-dht22">Wokwi DHT22 reference</a></p><h3>The MicroPython program</h3><p>Here is the supplied example with its attribution preserved and formatting cleaned up. Its behavior is unchanged, including the one-second simulation loop.</p><pre>&quot;&quot;&quot;<br>MicroPython IoT Weather Station Example for Wokwi.com</pre><pre>To view the data:</pre><pre>1. Go to <a href="http://www.hivemq.com/demos/websocket-client/">http://www.hivemq.com/demos/websocket-client/</a><br>2. Click &quot;Connect&quot;<br>3. Under Subscriptions, click &quot;Add New Topic Subscription&quot;<br>4. In the Topic field, type &quot;wokwi-weather&quot; then click &quot;Subscribe&quot;</pre><pre>Now click on the DHT22 sensor in the simulation,<br>change the temperature/humidity, and you should see<br>the message appear on the MQTT Broker, in the &quot;Messages&quot; pane.</pre><pre>Copyright (C) 2022, Uri Shaked</pre><pre>https://wokwi.com/arduino/projects/322577683855704658<br>&quot;&quot;&quot;</pre><pre>import network<br>import time<br>from machine import Pin<br>import dht<br>import ujson<br>from umqtt.simple import MQTTClient</pre><pre># MQTT Server Parameters<br>MQTT_CLIENT_ID = &quot;micropython-weather-demo&quot;<br>MQTT_BROKER = &quot;broker.mqttdashboard.com&quot;<br>MQTT_USER = &quot;&quot;<br>MQTT_PASSWORD = &quot;&quot;<br>MQTT_TOPIC = &quot;wokwi-weather&quot;</pre><pre>sensor = dht.DHT22(Pin(15))</pre><pre>print(&quot;Connecting to WiFi&quot;, end=&quot;&quot;)<br>sta_if = network.WLAN(network.STA_IF)<br>sta_if.active(True)<br>sta_if.connect(&#39;Wokwi-GUEST&#39;, &#39;&#39;)<br>while not sta_if.isconnected():<br>    print(&quot;.&quot;, end=&quot;&quot;)<br>    time.sleep(0.1)<br>print(&quot; Connected!&quot;)</pre><pre>print(&quot;Connecting to MQTT server... &quot;, end=&quot;&quot;)<br>client = MQTTClient(<br>    MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD<br>)<br>client.connect()<br>print(&quot;Connected!&quot;)</pre><pre>prev_weather = &quot;&quot;<br>while True:<br>    print(&quot;Measuring weather conditions... &quot;, end=&quot;&quot;)<br>    sensor.measure()<br>    message = ujson.dumps({<br>        &quot;temp&quot;: sensor.temperature(),<br>        &quot;humidity&quot;: sensor.humidity(),<br>    })<br>    if message != prev_weather:<br>        print(&quot;Updated!&quot;)<br>        print(&quot;Reporting to MQTT topic {}: {}&quot;.format(MQTT_TOPIC, message))<br>        client.publish(MQTT_TOPIC, message)<br>        prev_weather = message<br>    else:<br>        print(&quot;No change&quot;)<br>    time.sleep(1)</pre><h3>What each part does</h3><p>network.WLAN(network.STA_IF) puts the ESP32&#39;s Wi-Fi interface into station mode. The program activates it, connects to Wokwi&#39;s simulated Wokwi-GUEST network, and waits for connection. Real hardware needs your own network credentials.</p><p>MQTTClient then connects to broker.mqttdashboard.com. The example supplies empty credentials and uses the library&#39;s default non-TLS MQTT port, 1883. Its default publish settings are QoS 0 and unretained. A successful publish call does not establish that every subscriber received the message. <a href="https://github.com/micropython/micropython-lib/blob/master/micropython/umqtt.simple/umqtt/simple.py">MicroPython MQTT client source</a></p><p>Each loop calls sensor.measure() before reading temperature and humidity. ujson.dumps turns those values into a JSON string. The sensor&#39;s temperature is Celsius and humidity is percent relative humidity. <a href="https://docs.micropython.org/en/latest/esp8266/tutorial/dht.html">MicroPython DHT documentation</a></p><p>The string comparison against prev_weather controls publication. The first reading is sent because the previous value starts empty. A later reading is published only when its serialized contents differ. This suppresses repeated identical readings, though small sensor fluctuations can still trigger messages.</p><h3>Watch the messages arrive</h3><p>Open the linked Wokwi project. Before starting the simulation, subscribe to wokwi-weather on the same broker. The original example includes a HiveMQ browser-client link. If its current default connection points elsewhere, configure a compatible WebSocket endpoint for the same broker. A browser client cannot use raw MQTT TCP port 1883 directly.</p><p>Alternatively, with the Mosquitto client installed, subscribe from a terminal using the exact host in the script.</p><pre>mosquitto_sub -h broker.mqttdashboard.com -p 1883 -t &#39;wokwi-weather&#39; -v</pre><p>Start the simulation and change the sliders. The screenshot records the temperature moving from 24°C to −3°C, with humidity reaching 52%. One resulting message is:</p><pre>{&quot;humidity&quot;: 52.0, &quot;temp&quot;: -3.0}</pre><p>A subscriber that joins after publication waits for another change because these messages are unretained. If nothing arrives, change a slider again and check that both sides use the same broker and topic. For your own copy, choose a distinct topic such as your-handle/weather/esp32-01 and a unique client ID. Public topics are shared, so unrelated publishers can otherwise appear in your subscriber.</p><h3>Bring the payload into iOS</h3><p>The Swift model should match the actual JSON fields. This example sends temp and humidity. An iOS model expecting uptime or signal strength would fail to decode it.</p><pre>import Foundation</pre><pre>struct WeatherReading: Decodable {<br>    let temperature: Double<br>    let humidity: Double</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case temperature = &quot;temp&quot;<br>        case humidity<br>    }<br>}</pre><pre>// Pass the payload bytes from your MQTT client&#39;s message callback here.<br>func decodeWeather(payload: Data) throws -&gt; WeatherReading {<br>    try JSONDecoder().decode(WeatherReading.self, from: payload)<br>}</pre><p>In an MQTT client such as CocoaMQTT, subscribe to the same topic after the broker accepts the connection. Convert the message’s payload bytes to Data, call decodeWeather(payload:), and pass the result to a main-actor model that SwiftUI observes. Catch decoding errors so one malformed public message cannot replace a valid reading.</p><p>This snippet demonstrates payload decoding. An iOS dashboard also needs its MQTT connection, subscription callbacks, and scene lifecycle handling. Use a distinct iOS client ID so the phone and ESP32 can remain connected together. A useful first screen shows temperature, humidity, broker connectivity, and the time the last message arrived.</p><p>That final field needs careful wording. Because this firmware publishes only changes, a long silence can mean the weather is stable or that the device disconnected. Label it “Last received” until you add a heartbeat or availability protocol. A freshness timeout alone cannot distinguish those situations with this publisher.</p><h3>What changes before running on real hardware?</h3><p>Keep the one-second loop for reproducing this simulation. For a physical DHT22, use at least two seconds between measurements, following MicroPython’s guidance. Check the sensor or module’s power and pull-up requirements before wiring it. <a href="https://docs.micropython.org/en/latest/esp8266/tutorial/dht.html">DHT sampling guidance</a></p><p>The example also needs recovery logic for sensor errors and lost network connections. Its Wi-Fi wait has no deadline, MQTT connects once, and exceptions can stop the loop. Add bounded retries and backoff, then test failures deliberately. If availability matters, add periodic heartbeat messages and a Last Will configured before connecting.</p><p>Use authenticated TLS connections and topic permissions for deployed devices. Keep sensitive data off a public broker. If an iOS app needs updates while it is suspended, use a backend to keep ingesting readings and send appropriate notifications through APNs.</p><p>Starting with the simulator makes the data contract visible. Once you can explain why a message appears, why another is suppressed, and what silence means, you can build an iPhone interface that communicates those states clearly.</p><p><em>Code attribution: MicroPython weather-station example, Copyright © 2022 Uri Shaked, linked above. The screenshot was supplied for this article. The firmware was reviewed against the example and documentation; this walkthrough was not rerun against the live broker, and the iOS decoding snippet has not been tested in an integrated app.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f62e2f23611c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From ESP32 to SwiftUI: Build an iPhone IoT Dashboard with MQTT]]></title>
            <link>https://medium.com/@abdulsami923/from-esp32-to-swiftui-build-an-iphone-iot-dashboard-with-mqtt-8ba64d92067b?source=rss-2156f8dda5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba64d92067b</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[iphone]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Abdul Sami Sultan]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 20:42:34 GMT</pubDate>
            <atom:updated>2026-11-25T20:42:34.415Z</atom:updated>
            <content:encoded><![CDATA[<p>Connect an ESP32 to a SwiftUI app, then handle disconnects, stale readings, and the iOS app lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-ICwetDdtwTTI4XUqqfnQ.png" /><figcaption>Illustrative cover. The diagram shows message flow.</figcaption></figure><p>An ESP32 sends a reading. An iPhone displays it in SwiftUI. You can see the number change on screen.</p><p>Then someone pulls the USB cable. If the iPhone keeps displaying the last reading without saying the device has disappeared, its data can become misleading.</p><p>This walkthrough connects an ESP32 and an iPhone to the same local MQTT broker. We use Arduino for the firmware and SwiftUI for the dashboard. The board publishes its uptime and Wi-Fi signal strength every five seconds. A separate status topic lets subscribers learn when it connects and when the broker detects an unexpected disconnect.</p><h3>Give telemetry and availability separate jobs</h3><p>The ESP32 is an MQTT client. It publishes to a broker, and a terminal subscriber receives matching messages. Our iPhone app subscribes to those topics too. It connects to the broker directly for this lab. We use two topic names for one device.</p><pre>lab/esp32-lab-01/telemetry<br>lab/esp32-lab-01/status</pre><p>Telemetry carries a sequence number, milliseconds since boot, and signal strength in dBm. Status carries online or offline. The sequence resets after reboot, and uptime is a local counter rather than a wall-clock timestamp.</p><p>A retained status gives a new subscriber the broker’s latest stored value immediately. A Last Will asks the broker to publish offline if it detects that the connection ended unexpectedly. After connecting, the board publishes retained online, replacing that value. These are separate MQTT features that work together. <a href="https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html">MQTT 3.1.1 specification</a></p><h3>Set up a local broker</h3><p>You need a Wi-Fi-capable ESP32 development board, a USB cable, Arduino IDE with Espressif’s ESP32 board package, and the <strong>ArduinoMqttClient</strong> library by Arduino. Select your board and serial port. The library’s sender example explicitly supports the ESP32 architecture. <a href="https://github.com/arduino-libraries/ArduinoMqttClient/blob/master/examples/WiFiSimpleSender/WiFiSimpleSender.ino">Arduino’s sender example</a></p><p>Install Eclipse Mosquitto and its command-line clients on your computer using the installer or package manager for your operating system. Save the following as mosquitto.conf and start it with mosquitto -c mosquitto.conf -v. Stop any existing broker using port 1883 first.</p><pre>listener 1883 0.0.0.0<br>allow_anonymous true</pre><p>This configuration allows unauthenticated, unencrypted connections on the computer’s network interfaces. Use an isolated lab network, restrict firewall access to that network, and keep port 1883 off the public internet. The board and computer must be able to reach each other, which guest-network client isolation can prevent. Explicit listener configuration is necessary for remote clients in Mosquitto’s default setup. <a href="https://mosquitto.org/documentation/migrating-to-2-0/">Mosquitto listener guidance</a></p><p>In another terminal on the broker computer, start a subscriber before powering the board.</p><pre>mosquitto_sub -h localhost -p 1883 -t &#39;lab/esp32-lab-01/#&#39; -q 1 -v</pre><h3>Connect the ESP32 and publish</h3><p>Save this sketch as esp32_mqtt.ino. Replace the Wi-Fi credentials and broker address. Use the computer&#39;s LAN IP address for the broker; localhost on the ESP32 refers to the ESP32 itself. Give each board a unique device ID. This example uses no external sensor or GPIO wiring.</p><pre>#include &lt;WiFi.h&gt;<br>#include &lt;ArduinoMqttClient.h&gt;</pre><pre>// Isolated local-network tutorial. Replace all three values.<br>const char* WIFI_SSID = &quot;YOUR_WIFI_NAME&quot;;<br>const char* WIFI_PASSWORD = &quot;YOUR_WIFI_PASSWORD&quot;;<br>const char* BROKER_HOST = &quot;192.168.1.50&quot;;<br>const char* DEVICE_ID = &quot;esp32-lab-01&quot;; // Unique for every device.<br>const int BROKER_PORT = 1883;</pre><pre>WiFiClient network;<br>MqttClient mqtt(network);<br>String telemetryTopic;<br>String statusTopic;<br>unsigned long lastWifiAttempt = 0;<br>unsigned long lastMqttAttempt = 0;<br>unsigned long lastPublish = 0;<br>uint32_t sequence = 0;<br>bool attemptedMqtt = false;</pre><pre>bool publishText(const String&amp; topic, const char* payload, bool retained,<br>                 uint8_t qos) {<br>  if (!mqtt.beginMessage(topic.c_str(), retained, qos)) {<br>    return false;<br>  }<br>  mqtt.print(payload);<br>  return mqtt.endMessage() == 1;<br>}</pre><pre>void setup() {<br>  Serial.begin(115200);<br>  telemetryTopic = String(&quot;lab/&quot;) + DEVICE_ID + &quot;/telemetry&quot;;<br>  statusTopic = String(&quot;lab/&quot;) + DEVICE_ID + &quot;/status&quot;;</pre><pre>  WiFi.mode(WIFI_STA);<br>  WiFi.setAutoReconnect(true);<br>  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);<br>  lastWifiAttempt = millis();</pre><pre>  mqtt.setId(DEVICE_ID);<br>  mqtt.setKeepAliveInterval(15000); // ArduinoMqttClient uses milliseconds.<br>  mqtt.setConnectionTimeout(3000);<br>  mqtt.beginWill(statusTopic.c_str(), true, 1);<br>  mqtt.print(&quot;offline&quot;);<br>  mqtt.endWill();<br>}</pre><pre>void loop() {<br>  if (WiFi.status() != WL_CONNECTED) {<br>    network.stop();<br>    if (millis() - lastWifiAttempt &gt;= 10000UL) {<br>      lastWifiAttempt = millis();<br>      WiFi.reconnect();<br>    }<br>    delay(10);<br>    return;<br>  }</pre><pre>  if (!mqtt.connected()) {<br>    if (attemptedMqtt &amp;&amp; millis() - lastMqttAttempt &lt; 5000UL) {<br>      delay(10);<br>      return;<br>    }<br>    attemptedMqtt = true;<br>    bool connected = mqtt.connect(BROKER_HOST, BROKER_PORT);<br>    lastMqttAttempt = millis();<br>    if (!connected) {<br>      Serial.printf(&quot;MQTT connect error: %d\n&quot;, mqtt.connectError());<br>      return;<br>    }<br>    if (!publishText(statusTopic, &quot;online&quot;, true, 1)) {<br>      Serial.println(&quot;Could not confirm online status&quot;);<br>      mqtt.stop();<br>      return;<br>    }<br>    Serial.println(&quot;MQTT connected&quot;);<br>  }</pre><pre>  mqtt.poll(); // Service incoming packets and keepalive regularly.<br>  if (mqtt.connected() &amp;&amp; millis() - lastPublish &gt;= 5000UL) {<br>    lastPublish = millis();<br>    char payload[112];<br>    snprintf(payload, sizeof(payload),<br>             &quot;{\&quot;seq\&quot;:%lu,\&quot;uptime_ms\&quot;:%lu,\&quot;rssi_dbm\&quot;:%ld}&quot;,<br>             static_cast&lt;unsigned long&gt;(sequence++), millis(),<br>             static_cast&lt;long&gt;(WiFi.RSSI()));<br>    if (!publishText(telemetryTopic, payload, false, 0)) {<br>      Serial.println(&quot;Telemetry send failed&quot;);<br>      mqtt.stop();<br>    }<br>  }<br>  delay(1);<br>}</pre><p>The loop checks Wi-Fi before attempting MQTT. Failed MQTT connections are retried after five seconds, and telemetry uses elapsed-time checks. Individual connection attempts and QoS 1 acknowledgement waits can still block. This small example is unsuitable for a loop with strict timing deadlines. Espressif documents the Wi-Fi station and reconnect APIs used here. <a href="https://docs.espressif.com/projects/arduino-esp32/en/latest/api/wifi.html">ESP32 Wi-Fi API</a></p><p>Keep calling mqtt.poll() so the client can process packets and keepalive traffic. This library takes keepalive and connection timeouts in milliseconds. Its message API supports retained messages, QoS selection, and configuring a Will before connecting. <a href="https://github.com/arduino-libraries/ArduinoMqttClient/blob/master/src/MqttClient.h">ArduinoMqttClient API</a></p><h3>Bring the readings into SwiftUI</h3><p>Create an iOS 17 or later SwiftUI app in Xcode. Add https://github.com/emqx/CocoaMQTT.git through Package Dependencies, select version 2.4.0 using an Up to Next Major Version rule, and link the CocoaMQTT product to the app target. This example uses the MQTT 3.1.1 client. <a href="https://github.com/emqx/CocoaMQTT">CocoaMQTT installation guidance</a></p><p>In the target’s Info settings, add Privacy - Local Network Usage Description (NSLocalNetworkUsageDescription) with the value <em>Connect to your local MQTT broker to display ESP32 readings.</em> Run on a physical iPhone on the same reachable LAN and allow local-network access when asked. If access is denied, change it in Settings and press Reconnect. This example connects to a known IP directly. Bonjour declarations are required when browsing or registering Bonjour services. Apple&#39;s privacy checks apply across networking APIs. <a href="https://developer.apple.com/documentation/technotes/tn3179-understanding-local-network-privacy">Apple local-network privacy guidance</a></p><p>Add ESP32Dashboard.swift to the app target. Set its broker IP to match the firmware, then replace the generated app&#39;s root view with ESP32Dashboard() inside its existing WindowGroup. Keep the generated @main app entry point.</p><p>The model owns the MQTT connection and incoming data. The view reads its published properties. We track broker connectivity separately from device availability, because losing the phone’s broker connection leaves device availability unknown. We also track when valid telemetry last arrived. A retained online status alone cannot establish that the board is producing fresh readings.</p><pre>import SwiftUI<br>import Combine<br>import Foundation<br>@preconcurrency import CocoaMQTT</pre><pre>struct Telemetry: Decodable {<br>    let seq: UInt32<br>    let uptime_ms: UInt32<br>    let rssi_dbm: Int<br>}</pre><pre>@MainActor<br>final class DeviceMonitor: ObservableObject {<br>    @Published private(set) var brokerState = &quot;Disconnected&quot;<br>    @Published private(set) var deviceState = &quot;Unknown&quot;<br>    @Published private(set) var telemetry: Telemetry?<br>    @Published private(set) var lastReceived: Date?</pre><pre>    private var client: CocoaMQTT?<br>    private let host = &quot;192.168.1.50&quot; // Your broker computer&#39;s LAN IP.<br>    private let baseTopic = &quot;lab/esp32-lab-01&quot;</pre><pre>    func connect() {<br>        guard client == nil else { return }<br>        brokerState = &quot;Connecting&quot;<br>        deviceState = &quot;Unknown&quot;<br>        lastReceived = nil</pre><pre>        let mqtt = CocoaMQTT(<br>            clientID: &quot;ios-\(UUID().uuidString)&quot;, host: host, port: 1883<br>        )<br>        mqtt.delegateQueue = .main<br>        mqtt.keepAlive = 15 // CocoaMQTT uses seconds.<br>        mqtt.cleanSession = true<br>        mqtt.autoReconnect = true</pre><pre>        // All callbacks below run on the explicitly selected main queue.<br>        mqtt.didConnectAck = { [weak self] mqtt, ack in<br>            MainActor.assumeIsolated {<br>                guard let self, self.client === mqtt else { return }<br>                guard ack == .accept else {<br>                    self.brokerState = &quot;Connection rejected&quot;<br>                    return<br>                }<br>                self.brokerState = &quot;Connected&quot;<br>                mqtt.subscribe(self.baseTopic + &quot;/status&quot;, qos: .qos1)<br>                mqtt.subscribe(self.baseTopic + &quot;/telemetry&quot;, qos: .qos0)<br>            }<br>        }<br>        mqtt.didReceiveMessage = { [weak self] mqtt, message, _ in<br>            MainActor.assumeIsolated {<br>                guard let self, self.client === mqtt else { return }<br>                if message.topic == self.baseTopic + &quot;/status&quot; {<br>                    switch message.string {<br>                    case &quot;online&quot;: self.deviceState = &quot;Online&quot;<br>                    case &quot;offline&quot;: self.deviceState = &quot;Offline&quot;<br>                    default: self.deviceState = &quot;Unknown&quot;<br>                    }<br>                } else if message.topic == self.baseTopic + &quot;/telemetry&quot; {<br>                    do {<br>                        let sample = try JSONDecoder().decode(<br>                            Telemetry.self, from: Data(message.payload)<br>                        )<br>                        self.telemetry = sample<br>                        self.lastReceived = Date()<br>                    } catch {<br>                        // Malformed payloads never refresh the freshness clock.<br>                        print(&quot;Ignored invalid telemetry: \(error)&quot;)<br>                    }<br>                }<br>            }<br>        }<br>        mqtt.didDisconnect = { [weak self] mqtt, _ in<br>            MainActor.assumeIsolated {<br>                guard let self, self.client === mqtt else { return }<br>                self.brokerState = &quot;Disconnected&quot;<br>                self.deviceState = &quot;Unknown&quot;<br>                self.lastReceived = nil<br>            }<br>        }<br>        client = mqtt<br>        if !mqtt.connect() {<br>            brokerState = &quot;Could not start connection&quot;<br>            client = nil<br>        }<br>    }</pre><pre>    func disconnect() {<br>        let previous = client<br>        client = nil // Ignore callbacks belonging to the previous connection.<br>        previous?.autoReconnect = false<br>        previous?.disconnect()<br>        brokerState = &quot;Disconnected&quot;<br>        deviceState = &quot;Unknown&quot;<br>        lastReceived = nil<br>    }</pre><pre>    func reconnect() {<br>        disconnect()<br>        connect()<br>    }</pre><pre>    func freshness(at now: Date) -&gt; String {<br>        guard brokerState == &quot;Connected&quot;, let lastReceived else {<br>            return &quot;Awaiting fresh telemetry&quot;<br>        }<br>        return now.timeIntervalSince(lastReceived) &lt; 15 ? &quot;Fresh&quot; : &quot;Stale&quot;<br>    }<br>}</pre><pre>@MainActor<br>struct ESP32Dashboard: View {<br>    @StateObject private var monitor = DeviceMonitor()<br>    @Environment(\.scenePhase) private var scenePhase</pre><pre>    var body: some View {<br>        NavigationStack {<br>            TimelineView(.periodic(from: .now, by: 1)) { context in<br>                Form {<br>                    LabeledContent(&quot;Broker&quot;, value: monitor.brokerState)<br>                    LabeledContent(&quot;Device&quot;, value: monitor.deviceState)<br>                    LabeledContent(&quot;Data&quot;, value: monitor.freshness(at: context.date))<br>                    if let sample = monitor.telemetry {<br>                        Section(&quot;Last received reading&quot;) {<br>                            LabeledContent(&quot;Signal&quot;, value: &quot;\(sample.rssi_dbm) dBm&quot;)<br>                            LabeledContent(&quot;Uptime&quot;, value: &quot;\(sample.uptime_ms / 1000) s&quot;)<br>                            LabeledContent(&quot;Sequence&quot;, value: &quot;\(sample.seq)&quot;)<br>                        }<br>                    }<br>                    Button(&quot;Reconnect&quot;) { monitor.reconnect() }<br>                        .disabled(scenePhase != .active)<br>                }<br>            }<br>            .navigationTitle(&quot;ESP32 Monitor&quot;)<br>        }<br>        .onChange(of: scenePhase, initial: true) { _, phase in<br>            if phase == .active {<br>                monitor.connect()<br>            } else {<br>                monitor.disconnect()<br>            }<br>        }<br>    }<br>}</pre><p>The callback queue is explicitly set to the main queue. MainActor.assumeIsolated bridges that documented queue guarantee into the model&#39;s main-actor isolation. It asserts the guarantee rather than dispatching work. Keep that queue configuration when adapting the sample. Each callback also checks that it belongs to the current client, so an old disconnect callback cannot overwrite a newer connection. <a href="https://github.com/emqx/CocoaMQTT/blob/2.4.0/Source/CocoaMQTT.swift">Versioned CocoaMQTT callback API</a></p><p>TimelineView reevaluates the freshness label every second. Without a time-driven update, a screen could keep saying Fresh after messages stop. Fifteen seconds is a chosen threshold for this lab&#39;s five-second telemetry interval. Set it according to your device&#39;s expected cadence and tolerance for missed readings. Invalid JSON leaves the last valid reading visible and never refreshes its receive time.</p><p>When the scene becomes inactive or enters the background, the sample disconnects and reports device availability as unknown. Returning to the foreground connects again, resubscribes after acknowledgement, and waits for fresh telemetry. A retained status may arrive immediately, while unretained readings arrive on the next publish. Keeping a normal MQTT socket open does not grant an iOS app continuous background execution. A deployed service can ingest telemetry independently and use APNs for appropriate user notifications. <a href="https://developer.apple.com/documentation/uikit/extending-your-app-s-background-execution-time">Apple background execution guidance</a></p><h3>Test the whole path on an iPhone</h3><p>Open the serial monitor at 115200 baud. After connection, the subscriber should show output shaped like this. The numbers are illustrative.</p><pre>lab/esp32-lab-01/status online<br>lab/esp32-lab-01/telemetry {&quot;seq&quot;:0,&quot;uptime_ms&quot;:5100,&quot;rssi_dbm&quot;:-58}</pre><ol><li><strong>Check the iPhone.</strong> Confirm Broker Connected, Device Online, and Data Fresh. Compare its signal and sequence values with the terminal subscriber.</li><li><strong>Pull the USB cable.</strong> Leave the broker and subscriber running. After the broker detects the lost connection, look for status offline. Detection takes time and depends on transport and keepalive behavior. The iPhone should eventually show Offline. Its freshness label becomes Stale after fifteen seconds without valid telemetry, even before the Will arrives.</li><li><strong>Start another subscriber.</strong> It should receive the retained offline status. Telemetry is unretained, so it should receive no old reading from that topic.</li><li><strong>Reconnect power.</strong> Look for online status and new telemetry. The sequence and uptime restart.</li><li><strong>Restart the broker.</strong> The board should reconnect and republish online status. With this configuration, retained state is held in memory and can disappear when the broker restarts.</li><li><strong>Interrupt the phone connection.</strong> Its broker state should eventually change to Disconnected and device availability to Unknown. The last reading stays labeled as last received.</li><li><strong>Background and reopen the app.</strong> Confirm it reconnects, receives status again, and waits for a new reading before showing Fresh. Deny local-network permission once and test the recovery path too.</li></ol><p>The Last Will covers an unexpected disconnect while the broker is available. A graceful MQTT disconnect suppresses it. A broker failure also prevents that broker from publishing a Will during the outage. A dashboard should therefore track its own broker connection and how recently it received device telemetry.</p><h3>Decide which messages may be lost</h3><p>The sketch sends telemetry at QoS 0, where loss is possible. A missed signal-strength sample may be acceptable when another arrives five seconds later. It sends status at QoS 1, which provides at-least-once delivery on that MQTT hop and can produce duplicates. A broker acknowledgement does not confirm that a dashboard displayed the message or a database committed it. <a href="https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html">MQTT delivery semantics</a></p><p>For deployment, use TLS with certificate validation, device credentials, and topic permissions. Give each iPhone its own authorized access, and keep broker administration credentials out of the app. The direct local-broker connection here is a lab architecture. Remote access needs a secured reachable service, often with a backend that owns device ingestion and authorization. Add exponential reconnect backoff with jitter so many boards do not retry together. Define freshness using backend receive times or a synchronized device clock. If readings must survive an outage, add a bounded durable queue and define how the backend handles duplicates. A retained message stores the latest value for a topic, so historical telemetry needs a separate storage design.</p><p>The next useful test is simple. Leave the ESP32 powered, interrupt its Wi-Fi, and watch what the subscriber learns. Then ask whether the eventual dashboard gives someone enough information to act on the reading.</p><p><em>Validation note: the APIs were checked against official documentation and library source. The firmware and Swift code have not been compiled or exercised together on an ESP32 and iPhone in this environment. Perform the tests above on your hardware before treating the walkthrough as a verified build.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba64d92067b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your MVVM Architecture Still Feels Like MVC]]></title>
            <link>https://medium.com/@abdulsami923/why-your-mvvm-architecture-still-feels-like-mvc-4bb6961baf5a?source=rss-2156f8dda5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bb6961baf5a</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Abdul Sami Sultan]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 21:27:28 GMT</pubDate>
            <atom:updated>2026-11-12T21:27:28.917Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuFWG5JWahiQJGv5f7SKBg.png" /></figure><p><em>Moving code into a ViewModel doesn’t automatically make your iOS application scalable, testable, or maintainable.</em></p><p>After 5+ years of developing native iOS applications, I’ve learned that <strong>adopting an architecture is easy. Applying it correctly is where the real engineering challenge begins.</strong></p><p>During my experience working on an enterprise iOS application, Connect by VL, our team faced a common problem: a legacy MVC architecture that had become increasingly difficult to maintain as the application grew.</p><p>ViewControllers were responsible for almost everything:</p><ul><li>Handling UI interactions.</li><li>Making API requests.</li><li>Parsing responses.</li><li>Managing business rules.</li><li>Updating application state.</li><li>Handling navigation.</li><li>Managing errors.</li></ul><p>As new features were introduced, ViewControllers became larger, dependencies increased, and even small changes required careful consideration of potential regressions.</p><p>Naturally, we decided to move toward MVVM.</p><p>But that raised an important question:</p><p><strong>Are we actually improving the architecture, or just moving the same problems into a different class?</strong></p><h3>1. The Problem: Massive ViewControllers</h3><p>Consider a simplified example of a UIKit application that fetches and displays customer information.</p><pre>final class CustomersViewController: UIViewController {</pre><pre>    private var customers: [Customer] = []</pre><pre>    func loadCustomers() {<br>        URLSession.shared.dataTask(<br>            with: URL(string: &quot;https://api.example.com/customers&quot;)!<br>        ) { data, _, error in</pre><pre>            guard let data,<br>                  error == nil,<br>                  let customers = try? JSONDecoder().decode(<br>                    [Customer].self,<br>                    from: data<br>                  ) else {<br>                return<br>            }</pre><pre>            self.customers = customers.filter {<br>                $0.isActive<br>            }</pre><pre>            DispatchQueue.main.async {<br>                self.tableView.reloadData()<br>            }<br>        }.resume()<br>    }<br>}</pre><p><em>Simplified example illustrating architectural coupling rather than production-ready networking.</em></p><p>At first glance, this code might seem acceptable.</p><p>The API works. Data is fetched. Active customers are filtered. The UI updates.</p><p>But the ViewController is responsible for networking, decoding, business rules, state management, and presentation.</p><p>This creates several problems:</p><ol><li><strong>Tight coupling:</strong> UI components depend directly on networking implementation details.</li><li><strong>Poor testability:</strong> Testing filtering logic requires dealing with a ViewController.</li><li><strong>Limited reusability:</strong> Business rules are embedded in the presentation layer.</li><li><strong>Difficult maintenance:</strong> Changes to API behavior can affect UI code.</li><li><strong>Hidden dependencies:</strong> URLSession.shared is accessed directly, making controlled testing harder.</li></ol><p>This is one reason traditional MVC implementations often evolve into Massive ViewControllers.</p><h3>2. The First MVVM Migration Mistake</h3><p>A common reaction is to create a ViewModel and move most of the ViewController’s logic into it.</p><p>For example:</p><pre>final class CustomersViewModel {</pre><pre>    private(set) var customers: [Customer] = []</pre><pre>    func loadCustomers() async throws {<br>        let url = URL(<br>            string: &quot;https://api.example.com/customers&quot;<br>        )!</pre><pre>        let (data, _) = try await URLSession.shared.data(<br>            from: url<br>        )</pre><pre>        let response = try JSONDecoder().decode(<br>            [Customer].self,<br>            from: data<br>        )</pre><pre>        customers = response.filter { $0.isActive }<br>    }<br>}</pre><p>The ViewController is now smaller.</p><p>The networking code lives inside the ViewModel.</p><p>The UI and logic appear separated.</p><p><strong>But is the architecture actually better?</strong></p><p>Only partially.</p><p>The ViewModel still:</p><ul><li>Creates its own networking dependency.</li><li>Knows API endpoint details.</li><li>Handles response decoding.</li><li>Contains business filtering logic.</li><li>Manages presentation state.</li></ul><p>We’ve moved responsibilities, but we haven’t established clear boundaries between them.</p><p><strong>The result is a Massive ViewModel instead of a Massive ViewController.</strong></p><h3>3. The Better Approach: Separate Responsibilities</h3><p>During architectural refactoring, one of the most valuable lessons is that responsibilities should be divided according to their purpose, not merely relocated between files.</p><p>A maintainable implementation can separate three concerns:</p><ul><li><strong>Repository:</strong> Retrieves customer data and abstracts its source.</li><li><strong>Business logic:</strong> Determines which customers qualify for display.</li><li><strong>ViewModel:</strong> Coordinates loading and exposes UI-facing state.</li></ul><p>Let’s build a simplified example.</p><h3>Step 1: Define the model</h3><pre>struct Customer: Decodable, Sendable {<br>    let id: Int<br>    let name: String<br>    let isActive: Bool<br>}</pre><p>The model represents the data used by the application.</p><p>It doesn’t depend on UIKit or SwiftUI.</p><h3>Step 2: Introduce a repository abstraction</h3><pre>protocol CustomerRepository {<br>    func fetchCustomers() async throws -&gt; [Customer]<br>}</pre><p>Now the ViewModel no longer needs to know whether the data comes from REST APIs, local storage, or another source.</p><p>The implementation handles those details.</p><pre>struct RemoteCustomerRepository: CustomerRepository {</pre><pre>    let session: URLSession</pre><pre>    func fetchCustomers() async throws -&gt; [Customer] {<br>        let url = URL(<br>            string: &quot;https://api.example.com/customers&quot;<br>        )!</pre><pre>        let (data, response) = try await session.data(<br>            from: url<br>        )</pre><pre>        guard let response = response as? HTTPURLResponse,<br>              (200...299).contains(response.statusCode) else {<br>            throw URLError(.badServerResponse)<br>        }</pre><pre>        return try JSONDecoder().decode(<br>            [Customer].self,<br>            from: data<br>        )<br>    }<br>}</pre><p>The repository now owns networking and decoding.</p><p>The ViewModel doesn’t.</p><h3>Step 3: Move business rules into a dedicated component</h3><p>Suppose the application needs to display only active customers.</p><p>If that rule is part of the application’s business requirements, it can be separated from presentation logic.</p><pre>struct ActiveCustomerFilter {</pre><pre>    func execute(<br>        _ customers: [Customer]<br>    ) -&gt; [Customer] {<br>        customers.filter { $0.isActive }<br>    }<br>}</pre><p>This rule is now independent of the UI, networking, and application lifecycle.</p><p>It can also be tested without creating a ViewController or ViewModel.</p><p>Not every application needs a separate use-case or filter type for such a simple operation. The important decision is whether the rule represents reusable domain behavior or merely a screen-specific presentation choice.</p><h3>Step 4: Keep the ViewModel focused on UI state</h3><pre>@MainActor<br>final class CustomersViewModel: ObservableObject {</pre><pre>    @Published private(set) var customers: [Customer] = []<br>    @Published private(set) var isLoading = false<br>    @Published private(set) var errorMessage: String?</pre><pre>    private let repository: any CustomerRepository<br>    private let filter: ActiveCustomerFilter</pre><pre>    init(<br>        repository: any CustomerRepository,<br>        filter: ActiveCustomerFilter = .init()<br>    ) {<br>        self.repository = repository<br>        self.filter = filter<br>    }</pre><pre>    func loadCustomers() async {<br>        isLoading = true<br>        errorMessage = nil</pre><pre>        defer { isLoading = false }</pre><pre>        do {<br>            let result = try await repository.fetchCustomers()<br>            customers = filter.execute(result)<br>        } catch is CancellationError {<br>            // Cancellation is not a user-facing failure.<br>        } catch {<br>            errorMessage = &quot;Unable to load customers.&quot;<br>        }<br>    }<br>}</pre><p>Now the responsibilities are clearer.</p><p>The ViewModel coordinates the operation and exposes UI state.</p><p>The repository retrieves data.</p><p>The filter applies the business rule.</p><p>And the ViewController or SwiftUI View is responsible for rendering the result.</p><p><strong>That’s a meaningful architectural improvement — not simply an MVVM-shaped codebase.</strong></p><h3>4. Dependency Injection Makes Testing Practical</h3><p>One of the most important advantages of this approach is the ability to replace concrete dependencies during testing.</p><p>For example, instead of performing an actual network request, we can provide a mock repository.</p><pre>struct MockCustomerRepository: CustomerRepository {</pre><pre>    let customers: [Customer]</pre><pre>    func fetchCustomers() async throws -&gt; [Customer] {<br>        customers<br>    }<br>}</pre><p>And test the ViewModel:</p><pre>@MainActor<br>func testLoadCustomersFiltersInactiveCustomers() async {<br>    let repository = MockCustomerRepository(<br>        customers: [<br>            Customer(id: 1, name: &quot;Alice&quot;, isActive: true),<br>            Customer(id: 2, name: &quot;Bob&quot;, isActive: false)<br>        ]<br>    )</pre><pre>    let viewModel = CustomersViewModel(<br>        repository: repository<br>    )</pre><pre>    await viewModel.loadCustomers()</pre><pre>    XCTAssertEqual(viewModel.customers.count, 1)<br>    XCTAssertEqual(viewModel.customers.first?.name, &quot;Alice&quot;)<br>    XCTAssertFalse(viewModel.isLoading)<br>}</pre><p>No real API request.</p><p>No live backend.</p><p>No ViewController initialization.</p><p>The test verifies the behavior of the ViewModel using controlled data.</p><p>This is where dependency injection becomes valuable.</p><p><strong>Dependency injection isn’t just about following SOLID principles. It’s about making the software easier to change, test, and maintain.</strong></p><h3>5. Common MVVM Mistakes I Watch For</h3><p>After working with legacy and modern iOS architectures, these are some recurring issues worth watching during code reviews.</p><p><strong>Mistake 1: Networking directly inside ViewModels</strong></p><p>ViewModels that build URLs, decode responses, and manage API configurations become tightly coupled to infrastructure.</p><p><em>Better approach:</em> Introduce a networking or repository boundary where it provides practical value.</p><p><strong>Mistake 2: Putting every business rule into the ViewModel</strong></p><p>A ViewModel shouldn’t automatically become the home for validation, calculations, filtering, caching, and application-wide rules.</p><p><em>Better approach:</em> Extract business logic when it’s complex, reusable, or independently testable.</p><p><strong>Mistake 3: Using singletons for every dependency</strong></p><p>Global managers and shared services can introduce hidden dependencies and mutable state that complicate testing.</p><p><em>Better approach:</em> Prefer explicit dependency injection for services the component relies on.</p><p><strong>Mistake 4: Creating abstractions without a clear purpose</strong></p><p>Too many protocols, repositories, coordinators, and use cases can make a simple feature unnecessarily complicated.</p><p><em>Better approach:</em> Introduce abstractions to solve actual problems, not just to satisfy an architectural diagram.</p><p><strong>Mistake 5: Ignoring concurrency and state ownership</strong></p><p>Moving networking into a ViewModel doesn’t automatically solve thread safety or UI responsiveness.</p><p><em>Better approach:</em> Define clear actor-isolation boundaries, manage task cancellation, and keep expensive synchronous computations away from UI-critical execution.</p><h3>6. What I Learned From Refactoring an Enterprise iOS App</h3><p>Working on architectural improvements for Connect by VL reinforced several lessons.</p><p><strong>First, migration should be incremental.</strong></p><p>Rewriting an established application all at once increases risk. It’s usually more effective to improve architecture feature by feature while maintaining existing functionality.</p><p><strong>Second, improving testability is often more valuable than reducing file size.</strong></p><p>A 100-line ViewModel with tightly coupled dependencies can be harder to maintain than a larger ViewModel with clear responsibilities and testable boundaries.</p><p><strong>Third, architecture should support the team, not slow it down.</strong></p><p>When multiple developers are working on the same application, clear responsibilities, predictable dependencies, and consistent patterns make collaboration easier.</p><p><strong>Finally, architectural decisions should solve real problems.</strong></p><p>MVVM is not automatically better because a project contains ViewModels.</p><p>Its value comes from how effectively the architecture separates responsibilities and supports change.</p><h3>7. What Should Senior iOS Engineers Ask During Architecture Reviews?</h3><p>When reviewing an MVVM implementation, I find these questions more useful than simply checking whether the project follows a particular folder structure:</p><ul><li>Can we test the ViewModel without accessing the network?</li><li>Can we replace the data source without rewriting presentation logic?</li><li>Are business rules independent of UI frameworks where appropriate?</li><li>Are dependencies explicit?</li><li>Does the ViewModel own only the state and behavior relevant to its screen?</li><li>Are concurrency and cancellation handled correctly?</li><li>Would another engineer understand where new functionality belongs?</li></ul><p>These questions help reveal whether the architecture is genuinely maintainable.</p><h3>Final Takeaway</h3><p><strong>MVC isn’t inherently bad. MVVM isn’t automatically good.</strong></p><p>Both can produce maintainable applications when responsibilities and dependencies are managed thoughtfully.</p><p>And both can become difficult to maintain when boundaries are unclear.</p><p>The real goal of architectural refactoring isn’t to make the codebase look more modern.</p><p>It’s to make the application easier to understand, test, modify, and scale.</p><p><strong>A successful migration from MVC to MVVM shouldn’t just make your ViewControllers smaller. It should make future changes safer and easier.</strong></p><h3>Let’s Discuss</h3><p>Have you ever worked on an iOS application where ViewModels became just as complex as the ViewControllers they replaced?</p><p>How did your team approach separating responsibilities without overengineering the architecture?</p><p>I’d love to hear your experiences.</p><p><em>Engineering iOS at Scale — Notes from a Senior iOS Engineer</em></p><p>#SwiftUI #iOSDevelopment #AppleDeveloper #UIEngineering #AppDevelopment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bb6961baf5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Static Networking Layer Makes iOS Unit Testing Difficult]]></title>
            <link>https://medium.com/@abdulsami923/why-your-static-networking-layer-makes-ios-unit-testing-difficult-da2faf0a7180?source=rss-2156f8dda5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/da2faf0a7180</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[urlsessions]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[unit-test-framework]]></category>
            <dc:creator><![CDATA[Abdul Sami Sultan]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 21:26:26 GMT</pubDate>
            <atom:updated>2026-11-12T21:26:26.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DU9r6P2wbeWtpWUcm4MokQ.png" /></figure><p><em>Your API calls work. Your app ships. But can you test the networking behavior without making a real HTTP request?</em></p><p><strong>Engineering iOS Applications at Scale — Day 03</strong></p><p>After more than five years of developing native iOS applications, one lesson I’ve learned is that working code isn’t necessarily testable code.</p><p>While working on architectural improvements in enterprise iOS applications, including Connect by VL, one challenge was making existing networking components easier to test and maintain.</p><p>The application relied on networking patterns that coupled API calls directly to implementation details.</p><p>Everything worked during normal execution.</p><p>But when we wanted to test failure scenarios, mock API responses, or modify request behavior, things became more complicated.</p><p>This raises an important question:</p><p><strong>If your networking layer works perfectly in production, why should you change it?</strong></p><p>Because production correctness and architectural testability are two different concerns.</p><p>Let’s explore this through a common Swift implementation.</p><h3>1. The Problem: Static Networking Helpers</h3><p>A typical iOS project might start with a convenient networking utility:</p><pre>import Foundation</pre><pre>enum APIService {</pre><pre>    static func fetchUsers() async throws -&gt; [User] {<br>        let url = URL(<br>            string: &quot;https://api.example.com/users&quot;<br>        )!</pre><pre>        let (data, _) = try await URLSession.shared.data(<br>            from: url<br>        )</pre><pre>        return try JSONDecoder().decode(<br>            [User].self,<br>            from: data<br>        )<br>    }<br>}</pre><pre>struct User: Codable, Sendable, Equatable {<br>    let id: Int<br>    let name: String<br>}</pre><p>Using it inside a ViewModel is straightforward:</p><pre>@MainActor<br>final class UsersViewModel {</pre><pre>    private(set) var users: [User] = []</pre><pre>    func loadUsers() async throws {<br>        users = try await APIService.fetchUsers()<br>    }<br>}</pre><p>For a small application, this may appear perfectly reasonable.</p><p>The API call is centralized.</p><p>The implementation is easy to discover.</p><p>There is no object initialization.</p><p>And developers can call APIService.fetchUsers() from anywhere.</p><p><strong>So what’s the actual problem?</strong></p><p>The problem isn’t the static keyword itself.</p><p>It’s that callers depend directly on a concrete implementation that internally chooses its own network client.</p><p>We’ve created an architectural dependency that is difficult to replace during testing.</p><h3>2. Why This Becomes a Testing Problem</h3><p>Imagine writing a unit test for UsersViewModel.</p><p>You want to verify that the ViewModel correctly handles three scenarios:</p><ol><li>The server returns a valid list of users.</li><li>The server returns an HTTP 500 error.</li><li>The request succeeds but the JSON is malformed.</li></ol><p>With the static implementation, loadUsers() always calls the real APIService.</p><p>And APIService always uses URLSession.shared.</p><p>The test doesn’t control the transport dependency.</p><p>That creates several challenges.</p><p><strong>External dependency:</strong> Tests may require an accessible backend.</p><p><strong>Unpredictable responses:</strong> Server-side data and failures may change independently of the test.</p><p><strong>Limited error simulation:</strong> Reproducing timeouts, malformed responses, and authorization failures becomes unnecessarily difficult.</p><p><strong>Global configuration:</strong> Replacing shared network behavior can introduce interference between tests.</p><p>You can build workarounds, including URL loading interception, but the architectural dependency remains.</p><p><strong>A unit test should normally control the dependencies of the component being tested.</strong></p><h3>3. First Improvement: Abstract the HTTP Transport</h3><p>Rather than introducing a large networking framework, start with a small interface.</p><pre>import Foundation</pre><pre>protocol HTTPTransport: Sendable {<br>    func data(<br>        for request: URLRequest<br>    ) async throws -&gt; (Data, URLResponse)<br>}</pre><p>This protocol represents one capability:</p><p>Execute an HTTP request and return its response.</p><p>Next, implement it using URLSession.</p><pre>struct URLSessionTransport: HTTPTransport {</pre><pre>    let session: URLSession</pre><pre>    init(session: URLSession = .shared) {<br>        self.session = session<br>    }</pre><pre>    func data(<br>        for request: URLRequest<br>    ) async throws -&gt; (Data, URLResponse) {<br>        try await session.data(for: request)<br>    }<br>}</pre><p>Now the rest of our networking code depends on HTTPTransport, not directly on URLSession.shared.</p><p>This gives us two advantages:</p><ul><li>Production can continue using the standard Apple networking stack.</li><li>Tests can substitute a controlled implementation without making HTTP requests.</li></ul><p>The important change isn’t the protocol itself.</p><p><strong>It’s the ability to replace behavior at a clearly defined dependency boundary.</strong></p><h3>4. Build a Testable API Client</h3><p>Let’s introduce a dedicated API client.</p><pre>enum APIError: Error, Equatable {<br>    case invalidResponse<br>    case httpStatus(Int)<br>}</pre><pre>struct APIClient {</pre><pre>    private let transport: any HTTPTransport<br>    private let decoder = JSONDecoder()</pre><pre>    init(transport: any HTTPTransport) {<br>        self.transport = transport<br>    }</pre><pre>    func fetchUsers() async throws -&gt; [User] {<br>        let url = URL(<br>            string: &quot;https://api.example.com/users&quot;<br>        )!</pre><pre>        let request = URLRequest(url: url)</pre><pre>        let (data, response) = try await transport.data(<br>            for: request<br>        )</pre><pre>        guard let httpResponse = response<br>            as? HTTPURLResponse else {<br>            throw APIError.invalidResponse<br>        }</pre><pre>        guard (200...299).contains(<br>            httpResponse.statusCode<br>        ) else {<br>            throw APIError.httpStatus(<br>                httpResponse.statusCode<br>            )<br>        }</pre><pre>        return try decoder.decode(<br>            [User].self,<br>            from: data<br>        )<br>    }<br>}</pre><p>Notice what changed.</p><p>The API client still handles:</p><ul><li>Request construction.</li><li>Response validation.</li><li>JSON decoding.</li><li>Mapping HTTP failures to meaningful errors.</li></ul><p>But it no longer decides how HTTP requests are executed.</p><p>That’s the transport’s responsibility.</p><p>We can now test API behavior independently of the actual network.</p><h3>5. Creating a Mock HTTP Transport</h3><p>For deterministic unit tests, we can create a transport that returns a predefined response.</p><pre>struct StubTransport: HTTPTransport {</pre><pre>    let dataToReturn: Data<br>    let responseToReturn: URLResponse</pre><pre>    func data(<br>        for request: URLRequest<br>    ) async throws -&gt; (Data, URLResponse) {<br>        (dataToReturn, responseToReturn)<br>    }<br>}</pre><p>The mock doesn’t use URLSession.</p><p>It doesn’t access the internet.</p><p>It simply returns the data provided by the test.</p><p>This small abstraction allows us to test situations that would otherwise require modifying backend behavior.</p><h3>6. XCTest: Testing a Successful API Response</h3><p>Let’s verify that the API client correctly decodes a successful response.</p><pre>import XCTest</pre><pre>final class APIClientTests: XCTestCase {</pre><pre>    func testFetchUsersDecodesResponse() async throws {</pre><pre>        let json = &quot;&quot;&quot;<br>        [<br>            {&quot;id&quot;: 1, &quot;name&quot;: &quot;Alice&quot;},<br>            {&quot;id&quot;: 2, &quot;name&quot;: &quot;Bob&quot;}<br>        ]<br>        &quot;&quot;&quot;.data(using: .utf8)!</pre><pre>        let url = URL(<br>            string: &quot;https://api.example.com/users&quot;<br>        )!</pre><pre>        let response = HTTPURLResponse(<br>            url: url,<br>            statusCode: 200,<br>            httpVersion: nil,<br>            headerFields: nil<br>        )!</pre><pre>        let transport = StubTransport(<br>            dataToReturn: json,<br>            responseToReturn: response<br>        )</pre><pre>        let client = APIClient(<br>            transport: transport<br>        )</pre><pre>        let users = try await client.fetchUsers()</pre><pre>        XCTAssertEqual(users.count, 2)<br>        XCTAssertEqual(users[0].name, &quot;Alice&quot;)<br>        XCTAssertEqual(users[1].name, &quot;Bob&quot;)<br>    }<br>}</pre><p>This test executes the real API client logic.</p><p>But it never makes a network request.</p><p>We can verify JSON decoding without relying on server uptime, credentials, or an internet connection.</p><p>And because the test controls its input, it should produce the same result every time.</p><h3>7. XCTest: Simulating Server Failures</h3><p>The real benefit becomes clearer when testing error scenarios.</p><p>Suppose the server returns HTTP 500.</p><p>We want to confirm that the API client rejects the response rather than attempting to decode it as a successful result.</p><pre>func testFetchUsersThrowsOnServerError() async {</pre><pre>    let url = URL(<br>        string: &quot;https://api.example.com/users&quot;<br>    )!</pre><pre>    let response = HTTPURLResponse(<br>        url: url,<br>        statusCode: 500,<br>        httpVersion: nil,<br>        headerFields: nil<br>    )!</pre><pre>    let transport = StubTransport(<br>        dataToReturn: Data(),<br>        responseToReturn: response<br>    )</pre><pre>    let client = APIClient(<br>        transport: transport<br>    )</pre><pre>    do {<br>        _ = try await client.fetchUsers()<br>        XCTFail(&quot;Expected an HTTP error&quot;)<br>    } catch let error as APIError {<br>        XCTAssertEqual(error, .httpStatus(500))<br>    } catch {<br>        XCTFail(&quot;Unexpected error: \(error)&quot;)<br>    }<br>}</pre><p>No fake production endpoint.</p><p>No special server configuration.</p><p>No need to temporarily break the backend.</p><p>The test controls the HTTP response and verifies how the client reacts.</p><p>The same technique can be extended to invalid JSON, unauthorized requests, empty responses, and other edge cases.</p><p>Apple’s XCTest framework supports asynchronous test methods directly using async and await.</p><h3>8. Don’t Stop at Testing the API Client</h3><p>A testable HTTP client is useful, but ViewModels should generally depend on an application-level data interface rather than raw HTTP transport details.</p><p>For example:</p><pre>protocol UserRepository: Sendable {<br>    func fetchUsers() async throws -&gt; [User]<br>}</pre><pre>struct RemoteUserRepository: UserRepository {</pre><pre>    let client: APIClient</pre><pre>    func fetchUsers() async throws -&gt; [User] {<br>        try await client.fetchUsers()<br>    }<br>}</pre><p>Now the ViewModel depends on the repository.</p><pre>@MainActor<br>final class UsersViewModel {</pre><pre>    private let repository: any UserRepository</pre><pre>    private(set) var users: [User] = []</pre><pre>    init(repository: any UserRepository) {<br>        self.repository = repository<br>    }</pre><pre>    func loadUsers() async throws {<br>        users = try await repository.fetchUsers()<br>    }<br>}</pre><p>Our production dependency chain becomes:</p><p><strong>ViewModel → Repository → API Client → HTTP Transport → URLSession</strong></p><p>This is a useful separation because each boundary answers a different question.</p><p>The ViewModel asks: <em>What data should the screen display?</em></p><p>The repository asks: <em>Where does the application obtain its user data?</em></p><p>The API client asks: <em>How should this API request be constructed, validated, and decoded?</em></p><p>The transport asks: <em>How is the HTTP request executed?</em></p><p>Not every project needs every layer. The value comes from giving each dependency a clear purpose.</p><h3>9. XCTest: Testing the ViewModel Without Networking</h3><p>Now let’s test the ViewModel independently.</p><p>First, create a repository stub.</p><pre>struct StubUserRepository: UserRepository {</pre><pre>    let users: [User]</pre><pre>    func fetchUsers() async throws -&gt; [User] {<br>        users<br>    }<br>}</pre><p>Then write a ViewModel test.</p><pre>@MainActor<br>func testViewModelLoadsUsers() async throws {</pre><pre>    let repository = StubUserRepository(<br>        users: [<br>            User(id: 1, name: &quot;Alice&quot;)<br>        ]<br>    )</pre><pre>    let viewModel = UsersViewModel(<br>        repository: repository<br>    )</pre><pre>    try await viewModel.loadUsers()</pre><pre>    XCTAssertEqual(viewModel.users.count, 1)<br>    XCTAssertEqual(viewModel.users.first?.name, &quot;Alice&quot;)<br>}</pre><p>This test doesn’t know about:</p><ul><li>URLSession</li><li>API endpoints</li><li>JSON decoding</li><li>HTTP response codes</li><li>Network connectivity</li></ul><p>And that’s exactly the point.</p><p>The ViewModel test verifies presentation behavior.</p><p>The API client tests verify request handling and response processing.</p><p>We no longer need to exercise the entire networking stack just to test a screen.</p><h3>10. What About URLProtocol?</h3><p>Protocol-based dependency injection isn’t the only way to test networking code.</p><p>Apple provides URLProtocol, which can intercept requests handled by a configured URLSession.</p><p>For example:</p><pre>let configuration = URLSessionConfiguration.ephemeral</pre><pre>configuration.protocolClasses = [<br>    MockURLProtocol.self<br>]</pre><pre>let session = URLSession(<br>    configuration: configuration<br>)</pre><p>Here, MockURLProtocol represents a custom URLProtocol subclass implemented in the test target.</p><p>That approach can be particularly useful for validating:</p><ul><li>HTTP request headers.</li><li>Request bodies and methods.</li><li>Authentication behavior.</li><li>URL encoding.</li><li>Networking middleware.</li><li>Response handling through a real URLSession instance.</li></ul><p>However, URLProtocol isn&#39;t a complete replacement for dependency injection.</p><p>A test still needs a way to supply a configured session to the code under test.</p><p>That’s much easier when the network client already accepts its dependencies explicitly.</p><p>Also, custom URLProtocol subclasses aren&#39;t supported by background URL sessions.</p><p>A practical testing strategy is to use lightweight transport stubs for fast unit tests and configured URL sessions for tests that need to exercise more of the networking stack.</p><h3>11. Common Networking Architecture Mistakes</h3><p>These are several issues I watch for when reviewing iOS networking implementations.</p><p><strong>Mistake 1: Using </strong><strong>URLSession.shared everywhere</strong></p><p>It makes HTTP configuration and behavior harder to control independently.</p><p><em>Better approach:</em> Inject a session or transport when the feature needs isolated testing or customized behavior.</p><p><strong>Mistake 2: Making every API method static</strong></p><p>Static methods are convenient, but combining them with hidden, hard-coded dependencies makes substitution difficult.</p><p><em>Better approach:</em> Allow networking dependencies to be supplied explicitly. A static function can still be testable if it accepts the dependency it needs.</p><p><strong>Mistake 3: Mixing networking with ViewModel business logic</strong></p><p>When ViewModels build requests, decode JSON, manage authentication, and apply business rules, changes become more tightly coupled.</p><p><em>Better approach:</em> Keep transport and data-access concerns outside the presentation layer.</p><p><strong>Mistake 4: Testing only successful responses</strong></p><p>A networking layer must also handle failures predictably.</p><p><em>Better approach:</em> Cover HTTP errors, malformed JSON, transport failures, and cancellation where relevant.</p><p><strong>Mistake 5: Creating abstractions for everything</strong></p><p>A protocol for every class can introduce unnecessary complexity.</p><p><em>Better approach:</em> Add abstractions around dependencies that genuinely benefit from substitution, alternative implementations, or independent testing.</p><h3>12. The Architectural Trade-offs</h3><p>Does every networking layer need a repository, API client, transport protocol, and dependency injection container?</p><p><strong>No.</strong></p><p>For a small application with a few simple endpoints, injecting URLSession directly into a networking service may provide enough testability.</p><p>For larger enterprise applications, additional boundaries can be valuable when multiple features share authentication, caching, retries, observability, error handling, or API configuration.</p><p>But those benefits introduce costs:</p><ul><li>More types and files to maintain.</li><li>Additional dependency wiring.</li><li>More navigation between abstractions.</li><li>Potential overengineering if responsibilities aren’t clearly defined.</li></ul><p>There is also an important concurrency consideration.</p><p>With Swift 6’s strict concurrency checking, injected dependencies that cross actor boundaries may need appropriate Sendable conformance or actor isolation. A protocol abstraction doesn&#39;t automatically make shared mutable state safe.</p><p>Likewise, adding async/await doesn&#39;t eliminate the need to handle cancellation, task lifetimes, and UI state correctly.</p><p><strong>Good architecture is about controlling complexity — not maximizing the number of layers.</strong></p><h3>13. What I Learned From Refactoring Enterprise iOS Applications</h3><p>During architectural improvements to an enterprise application, one of the key challenges was reducing the coupling between networking, business logic, and presentation code.</p><p>Refactoring these responsibilities taught me several lessons.</p><p><strong>First, dependency injection is about control.</strong></p><p>Tests should decide what dependencies return, not depend on whatever a remote server happens to return.</p><p><strong>Second, testability should influence architecture early.</strong></p><p>When dependencies are tightly coupled, adding tests later often requires more refactoring than expected.</p><p><strong>Third, refactoring should be incremental.</strong></p><p>Replacing an entire networking layer in one release can introduce unnecessary risk. Moving feature by feature allows the team to verify behavior and maintain delivery continuity.</p><p><strong>Fourth, not every abstraction is worthwhile.</strong></p><p>The strongest designs are often those that introduce the fewest boundaries necessary to solve a real engineering problem.</p><p>These lessons are especially relevant when multiple engineers are contributing to a growing codebase.</p><h3>14. Questions Senior iOS Engineers Should Ask</h3><p>When reviewing a networking architecture, I consider the following questions:</p><ul><li>Can this feature be tested without internet access?</li><li>Can I simulate HTTP 401, 404, and 500 responses?</li><li>Can I test malformed or unexpected JSON?</li><li>Can I inject authentication and environment configuration?</li><li>Does the ViewModel know too much about HTTP?</li><li>Are networking errors mapped into meaningful application errors?</li><li>Is cancellation handled appropriately?</li><li>Can tests run independently without modifying shared global state?</li><li>Are we introducing abstractions that genuinely improve maintainability?</li></ul><p>These questions are often more useful than asking whether the application follows a particular architecture pattern.</p><h3>Final Takeaway</h3><p><strong>Static networking methods aren’t inherently the problem. Hidden dependencies are.</strong></p><p>A static API utility may be perfectly suitable for a small, straightforward application.</p><p>But as requirements grow, hard-coded dependencies can make testing, refactoring, and feature development increasingly difficult.</p><p>The goal isn’t to replace every static method with a protocol.</p><p>The goal is to create clear boundaries where behavior can be controlled, tested, and changed without affecting unrelated components.</p><p><strong>If you can’t test your networking behavior without contacting a real server, your architecture may be telling you something.</strong></p><h3>Let’s Discuss</h3><p>Have you ever worked on an iOS project where static API helpers made unit testing or refactoring unnecessarily difficult?</p><p>Did you introduce dependency injection, use URLProtocol, or take a different approach?</p><p>I’d love to hear what worked for your team.</p><p><em>Engineering iOS Applications at Scale — Notes from a Senior iOS Engineer</em></p><p>#iOSDevelopment #AppleDeveloper #SwiftUI #UIEngineering #AppDevelopment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da2faf0a7180" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>