<?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 Mohsin Khan on Medium]]></title>
        <description><![CDATA[Stories by Mohsin Khan on Medium]]></description>
        <link>https://medium.com/@mohsinkhan845?source=rss-cec377a306a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1ZL0oU8hiD0SVSQ1b20t5Q.jpeg</url>
            <title>Stories by Mohsin Khan on Medium</title>
            <link>https://medium.com/@mohsinkhan845?source=rss-cec377a306a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:48:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohsinkhan845/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[I Built a Resume Builder App in SwiftUI — Here’s Everything I Learned (Open Source)]]></title>
            <link>https://mohsinkhan845.medium.com/i-built-a-resume-builder-app-in-swiftui-heres-everything-i-learned-open-source-649f9c918706?source=rss-cec377a306a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/649f9c918706</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Mohsin Khan]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 16:58:12 GMT</pubDate>
            <atom:updated>2025-11-16T16:58:12.056Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Built a Resume Builder App in SwiftUI — Here’s Everything I Learned (Open Source)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CbjZMDmrceoGmJG8" /><figcaption>Photo by <a href="https://unsplash.com/@madebyswish?utm_source=medium&amp;utm_medium=referral">Emma Houghton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>SwiftUI + SwiftData + clean data modeling + PDF generation.</em></p><p>Git repository: <a href="https://github.com/mohsinbmwm3/Resume-Builder-iOS">https://github.com/mohsinbmwm3/Resume-Builder-iOS</a></p><p>For the past few weeks, I’ve been building something I’ve always wanted:<br>a <strong>clean, flexible resume builder app</strong> for iOS where <em>I</em> get to decide which sections appear, how they’re ordered, and what each section contains — without rigid templates or paywalls.</p><p>This project actually started in a very unplanned way.</p><p>I was sitting at an airport, waiting for my flight with about <strong>5–7 hours</strong> to kill. No agenda, no sprint, no pressure. Just me, my laptop, and a long layover.</p><p>And somewhere between a coffee and watching planes take off, I thought:</p><blockquote>“Why not build something genuinely useful? Something I’d actually use myself?”</blockquote><p>I opened Xcode right there in the boarding area and started sketching the first version of the data model — just a basic SectionModel, some ideas around dynamic resume sections, and a rough editor layout.</p><p>By the time I boarded the plane, the skeleton of the resume builder was already alive.</p><p>What was meant to be a way to pass time on a layover eventually turned into a fully structured SwiftUI + SwiftData project, a clean PDF generator, and something I now use as my real resume tool.</p><p>And honestly…<br>It became one of the most fun and meaningful side projects I’ve built.</p><p>It started as a small idea, but very quickly became a deep dive into:</p><ul><li>data modeling with SwiftData</li><li>dynamic, user-driven UI</li><li>and generating beautiful PDFs with SwiftUI</li></ul><p>This article is everything I learned along the way — and the entire project is open sourced.</p><h3>⭐ Why This Project Was Interesting</h3><p>I didn’t start this project to “fix resume builders” or reinvent anything.<br>I genuinely just wanted to build <strong>something useful</strong> to pass time during a long airport layover.</p><p>But as soon as I began sketching the data model, I realized something interesting:</p><p>Most resume apps follow a strict structure like:</p><ul><li>Summary</li><li>Experience</li><li>Skills</li><li>Education</li></ul><p>But when you actually build your own resume, you quickly notice that different people need different things.</p><p>Sometimes you want:</p><ul><li>“Projects” above “Experience”</li><li>A dedicated “Tech Stack”</li><li>A “Certifications” or “Awards” section</li><li>A “Leadership” section</li><li>Or even a completely custom section that no traditional template supports</li></ul><p>I wasn’t trying to solve a big problem — I just didn’t want my own resume to feel restricted.</p><p>So the natural challenge became:</p><blockquote>How do I let the user decide which sections they want, in what order,<br> while still keeping the UI simple and the PDF clean?</blockquote><p>I didn’t plan this part, but it slowly became the most fun part of the project — making the resume structure <strong>fully dynamic</strong>, but still beautifully formatted.</p><h3>🧱 THE DATA MODEL — The Core of Everything</h3><p>Before any UI existed, I spent time designing a <strong>deeply flexible yet simple</strong> model using SwiftData.</p><h4>💡 Goal:</h4><p>Allow any resume layout, any section, any order, any items — without making the logic messy.</p><h4>The final structure:</h4><pre>@Model<br>class SectionModel {<br>    @Attribute(.unique) var id: UUID<br>    var title: String                 // “Experience”, “Skills”, “Projects”, etc.<br>    var items: [ItemModel]            // List of entries<br>    var position: Int                 // User decides the order<br>}<br><br>@Model<br>class ItemModel {<br>    var id: UUID<br>    var headline: String              // Job Title, Project Name, Skill Category...<br>    var subheadline: String?          // Company, Location, or optional text<br>    var bullets: [String]             // Bullet points<br>}</pre><h3>Why this design?</h3><h4>1. Completely user-defined structure</h4><p>Nothing is hardcoded.<br>If the user wants:</p><ul><li>“Backend Experience”</li><li>followed by “Mobile Experience”</li><li>then “Projects”</li><li>then “Awards”</li></ul><p>…it just works.</p><h4>2. Predictable PDF output</h4><p>Because each section + item follows the same structure, the PDF renderer can format them perfectly without needing custom code per section.</p><h4>3. No duplication of logic</h4><p>Same views work for:</p><ul><li>Experience</li><li>Skills</li><li>Projects</li><li>Certifications</li><li>Custom sections</li></ul><h4>4. Clean reordering</h4><p>The position field ensures sections reorder smoothly:</p><ul><li>No UI hacks</li><li>No list drifting</li><li>Stable IDs prevent animations from going crazy</li></ul><p>This data model was the best decision in the entire project.</p><h3>🧩 USER EXPERIENCE DESIGN — Simple, but Surprisingly Hard</h3><p>Letting the user <strong>choose which sections their resume has</strong> changed the entire flow of the app.</p><h4>Instead of forcing a template, the app:</h4><p>✔ Shows a list of available section types<br> ✔ Lets users add only the ones they want<br> ✔ Allows unlimited custom sections<br> ✔ Lets users reorder everything with drag &amp; drop<br> ✔ Shows a real-time preview<br> ✔ Generates a PDF that exactly matches the preview</p><h4>The trickiest part:</h4><p><strong>Make it feel simple.</strong></p><p>Resume building can easily become overwhelming.<br>So every screen had to be stripped down to the essentials:</p><h4>A section contains:</h4><ul><li>a title</li><li>a list of items</li><li>an “Add item” button</li><li>a clean and minimal editor</li></ul><p>Nothing more.</p><h4>The Summary experience</h4><p>Most apps treat Summary like any other section, but that leads to weird UI.</p><p>So I built a dedicated experience:</p><ul><li>a multiline TextEditor</li><li>stored as a single ItemModel internally</li><li>behaves like a normal paragraph in preview/PDF</li><li>never shows bullets or sub-items</li></ul><p>Simple on the surface; internally structured for consistency.</p><h3>👀 Preview Mode — WYSIWYG, Not an Approximation</h3><p>A goal from day one:</p><blockquote>The PDF should look exactly like the preview screen.</blockquote><p>Not “almost same”, not “similar spacing”.<br><strong>Exact.</strong></p><p>So the preview uses the same building blocks as the PDF renderer:</p><ul><li>same typography</li><li>same layout components</li><li>same spacing logic</li><li>same data model</li></ul><p>Which means when you tap “Export PDF”, there’s zero surprise.</p><h3>📄 PDF Generation — The Fun Part</h3><p>The app uses SwiftUI’s PDFRenderer to produce a crisp, professional resume.</p><p>A few interesting challenges:</p><h4>1. Line wrapping</h4><p>SwiftUI sometimes splits lines awkwardly.<br>Fix:</p><pre>.fixedSize(horizontal: false, vertical: true)</pre><h4>2. Normalizing text</h4><p>Users often hit Enter in the Summary.<br>PDFs shouldn’t show random newlines.<br>Solution: normalize on export.</p><h4>3. Bullet formatting</h4><p>Bullet alignment across multiple lines is a science of its own.<br>I built a simple &amp; reliable custom component.</p><h4>4. Page balancing</h4><p>Sections gracefully flow across pages without cutting mid-item.</p><h4>5. Fonts</h4><p>PDFs sometimes render differently — fixed by explicitly specifying font design.</p><p>When everything came together, the final PDF looked as good as templates from Canva or Overleaf… but fully dynamic.</p><h3>🐛 Interesting Challenges I Solved</h3><p>Not the boring ones. The <em>interesting</em> ones:</p><h4>1. Sections jumping up/down while typing</h4><p>Happened because sorting ran on every keystroke.<br>Fixed by updating position only on reorder.</p><h4>2. Summary text appearing bold</h4><p>SwiftUI treated it as a “title-like block” → fixed by isolating styling.</p><h4>3. Editor vs Preview mismatch</h4><p>Fonts default differently inside TextEditor vs Text — fixed with explicit styles.</p><h4>4. Data disappearing on toggle</h4><p>SwiftData models must be updated via copies for change detection.</p><h4>5. Duplicate link rendering</h4><p>SwiftUI sometimes renders invisible links again in the PDF — solved by restructuring the header.</p><p>Each of these issues taught me a lot about SwiftUI’s rendering behavior.</p><h3>📱 Final App Capabilities</h3><p>✓ Add any section type<br> ✓ Create custom sections<br> ✓ Reorder sections freely<br> ✓ Edit every item with headlines, subheadlines &amp; bullets<br> ✓ Edit a proper multiline summary<br> ✓ Real preview mode<br> ✓ Beautiful PDF export<br> ✓ Offline, fast, and open source</p><p>Feels simple.<br>Under the hood… not so simple.<br>And that’s what made this project fun.</p><h3>📂 Open Source Repository</h3><p><a href="https://github.com/mohsinbmwm3/Resume-Builder-iOS">https://github.com/mohsinbmwm3/Resume-Builder-iOS</a></p><p>Includes:</p><ul><li>Full SwiftUI + SwiftData code</li></ul><h3>🚀 Closing Thoughts</h3><p>This wasn’t just a UI project — it was a data modeling project.</p><p>The entire experience became smooth only because the <strong>data model was designed intentionally</strong>:</p><ul><li>structured</li><li>predictable</li><li>flexible</li><li>minimal</li><li>template-agnostic</li></ul><p>Letting users choose their own sections made the project not only technically interesting, but <strong>a great study in UX simplification</strong>.</p><p>If you’re an iOS developer looking for a meaningful side project, I highly recommend building something that combines:</p><ul><li>structured data</li><li>user-driven customization</li><li>and document generation</li></ul><p>It will teach you things that tutorials never cover.</p><p>And if you want to build on top of mine — it’s open source and ready.</p><p><strong>Happy building.</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=649f9c918706" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Silent Push Notifications in iOS: Opportunities, Not Guarantees]]></title>
            <link>https://mohsinkhan845.medium.com/silent-push-notifications-in-ios-opportunities-not-guarantees-2f18f645b5d5?source=rss-cec377a306a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f18f645b5d5</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mohsin Khan]]></dc:creator>
            <pubDate>Fri, 07 Nov 2025 19:29:15 GMT</pubDate>
            <atom:updated>2025-11-07T19:29:15.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gGn8uewbdfyaGVhO" /><figcaption>Photo by <a href="https://unsplash.com/@nadineshaabana?utm_source=medium&amp;utm_medium=referral">Nadine E</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>“Silent pushes are </em>opportunities<em>, not </em>guarantees<em>.”</em></blockquote><p>If you’ve ever tried using <strong>silent push notifications</strong> for background sync or data refresh in your iOS app, you’ve probably seen it:<br> sometimes they work perfectly… and sometimes, they just don’t.</p><p>Let’s break down <strong>why</strong> that happens, how Apple decides whether to deliver or delay a silent push, and how you can design your app to handle it gracefully.</p><p>💡 <strong>New to Push Notifications?</strong><br>If you’re just getting started with implementing push notifications in your iOS app, check out my step-by-step guide:<br> 👉 <a href="https://mohsinkhan845.medium.com/push-notifications-in-modern-ios-apps-a-complete-guide-92249bcbf79b"><em>Push Notifications in Modern iOS Apps — A Complete Guide</em></a></p><h3>🔍 What Are Silent Push Notifications?</h3><p>Silent notifications are special push messages that <strong>wake your app in the background</strong> — without alerting the user — allowing you to fetch data or update state silently.</p><p>Here’s what a typical payload looks like:</p><pre>{<br>  &quot;aps&quot;: {<br>    &quot;content-available&quot;: 1<br>  },<br>  &quot;data&quot;: {<br>    &quot;syncType&quot;: &quot;userProfile&quot;<br>  }<br>}</pre><p>They require the Remote notifications background mode enabled in Xcode:</p><blockquote><strong><em>Xcode → Capabilities → Background Modes → Remote Notifications</em></strong></blockquote><p>When such a notification arrives, iOS decides if and when to launch your app in the background.<br> And that’s where most developers get surprised.</p><h3>⚙️ The Lifecycle of a Silent Push</h3><p>Below is a simplified explanation of what actually happens behind the scenes:</p><blockquote><em>iOS runs several checks before deciding whether your silent notification should execute or wait.</em></blockquote><p>Here’s the flow:</p><ol><li>Your <strong>server sends a silent push</strong> to Apple Push Notification Service (APNs).</li><li><strong>APNs</strong> delivers it to the user’s device.</li><li>The device performs:</li></ol><ul><li><strong>Frequency check</strong> (too many pushes = throttling)</li><li><strong>Network check</strong> (weak connection = delay)</li><li><strong>Power check</strong> (low power mode = deprioritized)</li><li><strong>Background budget check</strong> (is the app allowed to wake now?)</li></ul><ol><li>If everything passes, the app is briefly woken up in the background to run your code.</li></ol><p>That brief window is your opportunity — typically <strong>up to 30 seconds</strong> of execution time.</p><h3>🧩 When Things Go Wrong</h3><p>Silent pushes are not guaranteed. iOS may delay or drop them based on system conditions.</p><p>ConditionBehaviorReasonToo frequentThrottled or droppedAvoid power drain and abusePoor networkDelayedWait for stable connectivityLow Power ModeDelayed or droppedPreserve battery lifeBackground budget exhaustedDroppedSystem resource limitsApp force-quit by userOften droppedApp not allowed to wake</p><p>Even if APNs reports “Delivered”, your app might never receive it — because <strong>delivery to APNs ≠ execution on device</strong>.</p><h3>⚡ Why Apple Throttles Silent Notifications</h3><p>Apple doesn’t do this to frustrate developers — it’s all about system health.</p><p><strong>Reasons Apple throttles silent pushes:</strong></p><ul><li>🔋 <strong>Battery life protection</strong></li><li>🌐 <strong>Network efficiency</strong></li><li>🧱 <strong>System resource management</strong></li><li>🚫 <strong>Abuse prevention</strong> (e.g., spammy background syncs)</li></ul><p>From Apple’s docs:</p><blockquote><em>“Silent notifications are not guaranteed to be delivered and may be throttled by the system.”</em></blockquote><h3>💡 Best Practices for Developers</h3><p>Here’s how to work <em>with</em> iOS instead of against it:</p><p>✅ <strong>Use silent pushes sparingly.</strong><br> A few times per hour is fine — every minute is not.</p><p>✅ <strong>Always combine with Background Fetch.</strong><br> Silent push ≈ trigger; Background Fetch ≈ fallback.</p><p>✅ <strong>Never rely on them for real-time data.</strong><br> For chat, trading, or live tracking — use WebSockets or server-driven streams.</p><p>✅ <strong>Respect Low Power Mode.</strong><br> Queue tasks until the device is plugged in or awake.</p><p>✅ <strong>Log everything.</strong><br> Record when you send and when your app receives. The delta tells you if throttling occurs.</p><p>✅ <strong>Use priority = 5</strong> when sending via APNs.<br> Priority 10 is for visible alerts — silent pushes should always be lower priority.</p><h3>⚠️ Common Mistakes</h3><ul><li>❌ Using silent pushes for chat or live sync</li><li>❌ Assuming APNs delivery means execution</li><li>❌ Not enabling “Remote notifications” background mode</li><li>❌ Triggering pushes too often or in bursts</li><li>❌ Ignoring application(_:didReceiveRemoteNotification:fetchCompletionHandler:) timeout handling</li></ul><h3>🧭 Alternatives for Real-Time Updates</h3><p>If your app truly needs instant updates:</p><ul><li>Use <strong>WebSockets</strong> or <strong>server-sent events</strong></li><li>Leverage <strong>PushKit (VoIP)</strong> for allowed categories like calls</li><li>Or simply send a <strong>visible notification</strong> to prompt user action</li></ul><p>Remember, <strong>silent pushes aren’t for real-time</strong> — they’re for <em>eventual consistency</em>.</p><h3>🧠 Key Takeaway</h3><blockquote><em>Treat silent pushes as gentle nudges, not hard triggers.<br> iOS decides when — or if — your background task deserves to run.</em></blockquote><p>Design your app logic with <strong>resilience</strong>, <strong>fallbacks</strong>, and <strong>respect for system limits</strong>.<br> That’s the real secret to reliable background execution on iOS.</p><h3>📌 TL;DR</h3><ul><li>Silent pushes are <strong>not guaranteed</strong>.</li><li>iOS may <strong>throttle, delay, or drop</strong> them.</li><li>Use them <strong>sparingly</strong> for background refresh.</li><li>For urgent data, use <strong>visible notifications or real-time channels</strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f18f645b5d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Push Notifications in Modern iOS Apps — A Complete Guide]]></title>
            <link>https://mohsinkhan845.medium.com/push-notifications-in-modern-ios-apps-a-complete-guide-92249bcbf79b?source=rss-cec377a306a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/92249bcbf79b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Mohsin Khan]]></dc:creator>
            <pubDate>Fri, 07 Nov 2025 08:13:47 GMT</pubDate>
            <atom:updated>2025-11-07T19:30:28.363Z</atom:updated>
            <content:encoded><![CDATA[<h3>Push Notifications in Modern iOS Apps — A Complete Guide</h3><p>Push notifications are one of the most powerful ways to keep users engaged — when implemented right.<br>But between APNs, device tokens, permissions, and payload handling, many developers still find them intimidating.</p><p>Let’s simplify that.</p><h3>🧠 What Are Push Notifications?</h3><p>Push notifications are messages sent from your <strong>server (or a provider like Firebase)</strong> to <strong>Apple Push Notification Service (APNs)</strong>, which then delivers them to user devices.</p><p>They can:</p><ul><li>Show alerts, badges, or sounds</li><li>Update content silently in the background</li><li>Drive engagement or sync data</li></ul><h3>⚙️ The Three Layers of iOS Push Notifications</h3><p><strong>Client (your iOS app)</strong></p><ul><li>Registers for push notifications and gets a <em>device token</em></li></ul><p><strong>Server (your backend or provider)</strong></p><ul><li>Stores tokens and sends notifications via APNs</li></ul><p><strong>Apple Push Notification Service (APNs)</strong></p><ul><li>Handles delivery, retries, and prioritization</li></ul><h3>🧩 Step 1: Enable Capabilities</h3><p>In Xcode:</p><blockquote><strong><em>Signing &amp; Capabilities → + Capability → Push Notifications</em></strong></blockquote><p>If your app supports background updates (silent pushes):</p><blockquote><em>Enable </em><strong><em>Background Modes → Remote notifications</em></strong></blockquote><h3>🔑 Step 2: Request User Permission</h3><p>Ask for permission as soon as it makes sense — ideally after explaining why you need it.</p><pre>import UserNotifications<br><br>func requestPushPermission() {<br>    let center = UNUserNotificationCenter.current()<br>    center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in<br>        if let error = error {<br>            print(&quot;Permission error: \(error.localizedDescription)&quot;)<br>        } else {<br>            DispatchQueue.main.async {<br>                UIApplication.shared.registerForRemoteNotifications()<br>            }<br>        }<br>    }<br>}</pre><p>💡 <em>Tip:</em> Don’t ask for permission on the very first app launch.<br> Educate the user first — then request.</p><h4>🕓 When to Request Push Notification Permission</h4><h4>❌ Don’t: Ask on First Launch</h4><blockquote><em>You just installed the app. It immediately asks for notifications — before you’ve even done anything.</em></blockquote><p>This is one of the biggest mistakes developers make.</p><ul><li>The user doesn’t yet trust your app</li><li>They don’t know what kind of notifications they’ll receive</li><li>Most users instinctively hit “Don’t Allow”</li></ul><p>👉 Once denied, it’s <em>very hard</em> to recover — they must manually re-enable it from <strong>Settings → Notifications</strong>.</p><h4>✅ Do: Ask After Demonstrated Value</h4><p>The golden rule is:</p><blockquote><strong><em>Ask after you’ve delivered value and context</em></strong></blockquote><p>Let users experience what your app offers <strong>before</strong> requesting permission.</p><h4>💬 Use a “Soft Ask” (Pre-Prompt)</h4><p>Instead of directly triggering Apple’s system alert, show your own custom explainer first:</p><blockquote><em>“Would you like to receive instant updates when your order ships?”<br> [Allow] [Maybe Later]</em></blockquote><p>Only if the user taps <strong>Allow</strong>, then trigger the real system permission dialog.</p><p>This dramatically increases opt-in rates because:</p><ul><li>You educate before asking</li><li>You avoid the irreversible system “Don’t Allow” early on</li><li>You can show the pre-prompt multiple times (Apple’s system dialog only once)</li></ul><p>Example:</p><pre>func showPrePermissionPrompt() {<br>    let alert = UIAlertController(<br>        title: &quot;Stay Updated!&quot;,<br>        message: &quot;Would you like to get notifications about new features and updates?&quot;,<br>        preferredStyle: .alert<br>    )<br>    alert.addAction(UIAlertAction(title: &quot;Allow&quot;, style: .default) { _ in<br>        self.requestPushPermission()<br>    })<br>    alert.addAction(UIAlertAction(title: &quot;Later&quot;, style: .cancel))<br>    UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true)<br>}</pre><p>Then call your requestPushPermission() only if the user agrees.</p><h3>🔁 Step 3: Register for Remote Notifications</h3><p>Your app will receive a device token from APNs:</p><pre>func application(_ application: UIApplication,<br>                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {<br>    let tokenString = deviceToken.map { String(format: &quot;%02.2hhx&quot;, $0) }.joined()<br>    print(&quot;Device Token: \(tokenString)&quot;)<br>    // Send this token to your server<br>}</pre><p>Handle failure too:</p><pre>func application(_ application: UIApplication,<br>                 didFailToRegisterForRemoteNotificationsWithError error: Error) {<br>    print(&quot;Failed to register: \(error)&quot;)<br>}</pre><h3>🌐 Step 4: Configure Your Server</h3><p>Use Apple’s <strong>HTTP/2 APNs API</strong> to send notifications:</p><pre>curl -v \<br>  -d &#39;{&quot;aps&quot;:{&quot;alert&quot;:&quot;Hello from APNs!&quot;,&quot;sound&quot;:&quot;default&quot;}}&#39; \<br>  -H &quot;apns-topic: com.example.MyApp&quot; \<br>  -H &quot;authorization: bearer &lt;JWT&gt;&quot; \<br>  --http2 \<br>  https://api.push.apple.com/3/device/&lt;device_token&gt;</pre><p>If you’re using Firebase, OneSignal, or AWS SNS — they handle this part internally.</p><p>Just make sure you upload your <strong>APNs key (.p8)</strong> in their dashboard.</p><h3>📲 Step 5: Handle Notifications in App</h3><p>iOS delivers notifications differently depending on state:</p><p>App StateBehaviorForegroundHandled by UNUserNotificationCenterDelegateBackground Shown automatically by systemKilledShown automatically; tap launches appSilent pushdidReceiveRemoteNotification with background fetch</p><p>Here’s a simple delegate example:</p><pre>extension AppDelegate: UNUserNotificationCenterDelegate {<br>    func userNotificationCenter(_ center: UNUserNotificationCenter,<br>        willPresent notification: UNNotification,<br>        withCompletionHandler completionHandler:<br>        @escaping (UNNotificationPresentationOptions) -&gt; Void) {<br>        completionHandler([.banner, .sound])<br>    }<br>    func userNotificationCenter(_ center: UNUserNotificationCenter,<br>        didReceive response: UNNotificationResponse,<br>        withCompletionHandler completionHandler: @escaping () -&gt; Void) {<br>        let userInfo = response.notification.request.content.userInfo<br>        print(&quot;Tapped notification: \(userInfo)&quot;)<br>        completionHandler()<br>    }<br>}</pre><h3>⚙️ Step 6: Handling Silent Notifications (Background Fetch)</h3><p>For background work, implement:</p><pre>func application(_ application: UIApplication,<br>    didReceiveRemoteNotification userInfo: [AnyHashable : Any],<br>    fetchCompletionHandler completionHandler:<br>    @escaping (UIBackgroundFetchResult) -&gt; Void) {<br>    // Perform background task<br>    completionHandler(.newData)<br>}</pre><p>I have wrote a seperate guide on how to use silent notifications <a href="https://mohsinkhan845.medium.com/silent-push-notifications-in-ios-opportunities-not-guarantees-2f18f645b5d5">https://mohsinkhan845.medium.com/silent-push-notifications-in-ios-opportunities-not-guarantees-2f18f645b5d5</a></p><h3>🔒 Step 7: Test Pushes Locally</h3><p>You can test from terminal using xcrun:</p><pre>xcrun simctl push booted com.example.MyApp pushpayload.apns</pre><p>Where pushpayload.apns is a local JSON file:</p><pre>{<br>  &quot;aps&quot;: {<br>    &quot;alert&quot;: &quot;Test push!&quot;,<br>    &quot;sound&quot;: &quot;default&quot;<br>  }<br>}</pre><p>Or test directly from Firebase console for FCM-based setups.</p><h3>💡 Tips for a Robust Setup</h3><p>Use <strong>UNUserNotificationCenter</strong> for unified management<br>Handle <strong>token refreshes</strong> — tokens can change anytime<br>Support <strong>rich notifications</strong> (images, buttons) for better UX<br>Use <strong>category identifiers</strong> for custom actions<br>Don’t rely on <strong>silent pushes</strong> for real-time data</p><h3>🚀 Modern Add-Ons</h3><ul><li><strong>Push Notification Extensions:</strong><br> For modifying or enriching content before display<br> → Target: <em>Notification Service Extension</em></li><li><strong>Notification Content Extension:</strong><br> For building custom UI in notification banners</li><li><strong>Provisional Authorization (iOS 12+):</strong><br> Deliver notifications silently first, then request full permission later</li></ul><h3>🧭 Summary</h3><p>Push notifications aren’t just about alerts — they’re about communication, reliability, and respect for the user’s attention.<br>Modern iOS gives you the flexibility to deliver that — securely and efficiently.</p><p>When combined with the companion article on <strong>Silent Pushes</strong>, you’ll have a complete understanding of:</p><ul><li>Visible notifications (alerts, badges, sounds)</li><li>Background updates</li><li>System-level throttling behavior</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92249bcbf79b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evolution of Unique ID Generation in Distributed Systems]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://mohsinkhan845.medium.com/evolution-of-unique-id-generation-in-distributed-systems-a948c427b3ab?source=rss-cec377a306a1------2"><img src="https://cdn-images-1.medium.com/max/2278/1*aONbEqGz_BJg_n9Y_JpZKA.png" width="2278"></a></p><p class="medium-feed-snippet">&#x1F449; Free version of this article is available here</p><p class="medium-feed-link"><a href="https://mohsinkhan845.medium.com/evolution-of-unique-id-generation-in-distributed-systems-a948c427b3ab?source=rss-cec377a306a1------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://mohsinkhan845.medium.com/evolution-of-unique-id-generation-in-distributed-systems-a948c427b3ab?source=rss-cec377a306a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a948c427b3ab</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Mohsin Khan]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 16:07:41 GMT</pubDate>
            <atom:updated>2025-11-05T16:14:52.525Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Swift 6.2: Say Goodbye to ?? in String Interpolation]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">We&#x2019;ve all written something like this countless times:</p><p class="medium-feed-link"><a href="https://mohsinkhan845.medium.com/swift-6-2-say-goodbye-to-in-string-interpolation-0c31265eaa87?source=rss-cec377a306a1------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://mohsinkhan845.medium.com/swift-6-2-say-goodbye-to-in-string-interpolation-0c31265eaa87?source=rss-cec377a306a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c31265eaa87</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mohsin Khan]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 11:58:32 GMT</pubDate>
            <atom:updated>2025-11-05T16:15:48.193Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building SwiftlyImageLoader]]></title>
            <link>https://mohsinkhan845.medium.com/building-swiftlyimageloader-ec4a20f24300?source=rss-cec377a306a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec4a20f24300</guid>
            <category><![CDATA[iphone-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mohsin Khan]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 16:42:38 GMT</pubDate>
            <atom:updated>2025-08-31T16:42:38.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lrKjNzaLlUlzgDV7" /><figcaption>Photo by <a href="https://unsplash.com/@prince_perry?utm_source=medium&amp;utm_medium=referral">Perry Merrity II</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>A Fast, Lightweight Image Caching Library in Swift</h3><p>Github Repo: <a href="https://github.com/mohsinbmwm3/SwiftlyImageLoader/tree/main">https://github.com/mohsinbmwm3/SwiftlyImageLoader/tree/main</a></p><p>Modern iOS apps are image-heavy — from profile thumbnails and product banners to dynamic content fetched from remote APIs. Yet building a fast, memory-safe, and concurrency-friendly image loading mechanism still feels harder than it should be.</p><p>That’s exactly why I built <a href="https://github.com/mohsinbmwm3/SwiftlyImageLoader/tree/main"><strong>SwiftlyImageLoader</strong></a> — a Swift-native image loading library that’s:</p><ul><li>✅ Lightweight and modular</li><li>🚀 Powered by async/await and Swift Concurrency</li><li>📦 Backed by NSCache and disk cache for performance</li><li>💡 Pluggable with custom image transformers</li><li>🧪 Fully testable and production-ready</li></ul><p>This article dives deep into <strong>how and why </strong><a href="https://github.com/mohsinbmwm3/SwiftlyImageLoader/tree/main"><strong>SwiftlyImageLoader</strong></a><strong> was built</strong>, its <strong>architecture</strong>, real-world <strong>usage examples</strong>, and how it compares to popular solutions.</p><h4>Why Build Another Image Loader?</h4><p>Sure, libraries like SDWebImage and Kingfisher are great. But they come with:</p><ul><li>Large binaries</li><li>UIKit-centric APIs</li><li>Reactive or callback-based interfaces</li><li>Less control over memory and transform pipeline</li></ul><p>For modern apps — especially SwiftUI-based or those using Swift Concurrency — you want something clean, fast, and extensible.</p><p>So I built my own.</p><h4>⚙Core Features at a Glance</h4><ul><li>loadImage(from:) with built-in async pipeline</li><li>In-memory caching using NSCache</li><li>Optional disk cache (pluggable layer)</li><li>Image transformation hooks (resize, tint, etc.)</li><li>TTL-based cache expiration</li><li>Cancellation support for reused cells</li><li>SwiftUI support out of the box</li></ul><h4>Architecture Overview</h4><pre>┌────────────┐<br>│ View Layer │<br>└────┬───────┘<br>     ↓<br>┌──────────────┐<br>│ ImageLoader  │╌╌ calls → loadImage()<br>└────┬─────────┘<br>     ↓<br>┌──────────────┐             ┌─────────────────┐<br>│ MemoryCache  │.  ◄───────► │ DiskCache (opt) │<br>└──────────────┘             └─────────────────┘<br>     ↓<br>┌────────────────┐<br>│ ImageDecoder   │<br>└────────────────┘</pre><p>Each layer is cleanly separated:</p><ul><li><strong>ImageLoader</strong> is the orchestrator.</li><li><strong>MemoryCache</strong> uses NSCache to store decoded images.</li><li><strong>DiskCache</strong> can be plugged in with custom policy.</li><li><strong>ImageDecoder</strong> performs transformation if needed.</li></ul><p>All of this is powered by modern Swift:</p><pre>let image = try await imageLoader.loadImage(from: url)</pre><h4>NSCache in Action</h4><p>NSCache is a core part of our memory strategy. Here&#39;s a simplified view:</p><pre>final class ImageMemoryCache {<br>    private let cache = NSCache&lt;NSString, UIImage&gt;()<br>    func image(forKey key: String) -&gt; UIImage? {<br>        cache.object(forKey: key as NSString)<br>    }<br>    func insertImage(_ image: UIImage, forKey key: String) {<br>        cache.setObject(image, forKey: key as NSString)<br>    }<br>}</pre><p>It gives us:</p><ul><li>Fast lookup for reuse (e.g., scrolling in a UITableView)</li><li>Automatic cleanup on memory warnings</li><li>No need to manage strong references manually</li></ul><h4>Transformers</h4><p>SwiftlyImageLoader supports image transformation with a simple protocol:</p><pre>protocol ImageTransformer {<br>    func transform(_ image: UIImage) -&gt; UIImage<br>}</pre><p>You can pass it like so:</p><pre>let image = try await imageLoader.loadImage(from: url, transformer: ResizeTransformer(size: .init(width: 80, height: 80)))</pre><p>Transformers can include:</p><ul><li>Resizing</li><li>Grayscale</li><li>Tints</li><li>Rounded corners</li></ul><h4>Performance and Testing</h4><ul><li>⚡ Scroll tests show <strong>60fps sustained</strong> even with large remote images</li><li>🧠 Memory is tightly controlled (thanks to NSCache eviction)</li><li>✅ All components unit tested: Cache, Loader, Transformer</li></ul><h4>Usage Example in SwiftUI</h4><pre>struct UserAvatarView: View {<br>    let url: URL<br>    @State private var image: UIImage?<br>    var body: some View {<br>        Group {<br>            if let img = image {<br>                Image(uiImage: img)<br>                    .resizable()<br>                    .aspectRatio(contentMode: .fit)<br>            } else {<br>                ProgressView()<br>            }<br>        }<br>        .task {<br>            image = try? await ImageLoader.shared.loadImage(from: url)<br>        }<br>    }<br>}</pre><h4>What’s Next</h4><ul><li>✅ Animated image support (GIF, WebP)</li><li>✅ Retry policies with exponential backoff</li><li>🧠 Memory pressure hooks</li><li>🔌 Pluggable disk backend (FileManager, SQLite, Realm)</li><li>📦 Swift Package Manager support</li></ul><h4>Get Started</h4><p>The project is open source you can find it here:<br> 👉 <a href="https://github.com/yourgithub/swiftlyimageloader">GitHub — SwiftlyImageLoader</a></p><p>Install via Swift Package Manager:</p><pre>.package(url: &quot;https://github.com/yourgithub/swiftlyimageloader.git&quot;, from: &quot;1.0.0&quot;)</pre><h4>❤️ Final Thoughts</h4><p>SwiftlyImageLoader is my attempt at creating a <strong>modern, Swift-native, zero-boilerplate image loader</strong> that works beautifully across UIKit and SwiftUI.</p><p>Whether you’re building a tiny utility app or a full-fledged eCommerce platform — image loading doesn’t have to be painful.</p><blockquote><em>Feel free to ⭐️ the repo, contribute PRs, or just give it a try and share feedback!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec4a20f24300" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Data Storage Made Simple]]></title>
            <link>https://mohsinkhan845.medium.com/ios-data-storage-made-simple-084f6ccf1f9e?source=rss-cec377a306a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/084f6ccf1f9e</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mohsin Khan]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 20:21:54 GMT</pubDate>
            <atom:updated>2025-08-29T20:21:54.779Z</atom:updated>
            <content:encoded><![CDATA[<p>When building modern iOS apps, one of the most common mistakes developers make is misusing storage APIs. Apple provides <strong>multiple storage mechanisms</strong>, each with its own purpose. Picking the wrong one can lead to <strong>sluggish apps, bloated memory, and even data loss</strong>.</p><p>In this article, I’ll break down the right tools for the job, with examples in <strong>Swift</strong> (and quick notes for <strong>Objective-C</strong>, since many codebases still mix both). I’ll also share issues I’ve seen when working on large-scale iOS apps in my career.</p><h3>🗂️ 1. Structured, Queryable Data → SwiftData / Core Data</h3><p>If your app needs <strong>structured entities, queries, relationships, or history tracking</strong>, <strong>SwiftData (iOS 17+)</strong> or <strong>Core Data (legacy/Obj-C friendly)</strong> is the right choice. Think of SwiftData/Core Data as your iOS app’s internal SQLite ORM — but fully integrated with SwiftUI, iCloud, undo/redo, background saving, versioning, etc.</p><h4>✅ Best for:</h4><ul><li>You have custom models with properties (title, date, status, etc.)</li><li>You need to <strong>query/filter/sort</strong> data (e.g., “All incomplete tasks, sorted by due date”)</li><li>You want <strong>relationships</strong> between entities (e.g., Project → Tasks)</li><li>You want <strong>offline support</strong> and eventual sync</li><li>You care about <strong>undo/redo</strong>, <strong>versioning</strong>, <strong>NSPersistentHistoryTracking</strong></li><li>You want <strong>schema evolution / migrations</strong> over time</li></ul><h4>❌ Avoid for:</h4><ul><li>Secrets (use Keychain)</li><li>Huge binaries (store file paths instead)</li><li>Temporary caches (use NSCache)</li></ul><h4>🧠 Real-World Example — Tasks &amp; Tags</h4><p>Let’s say we’re building a task manager. Each task:</p><ul><li>has a title, date, and completion status</li><li>may belong to a project</li><li>can have many tags</li></ul><h4>🔸 SwiftData Models</h4><pre>@Model<br>final class Task {<br>    var id = UUID()<br>    var title: String<br>    var isCompleted: Bool<br>    var createdAt: Date<br>    var project: Project?<br>    var tags: [Tag] = []<br>    init(title: String, project: Project?) {<br>        self.title = title<br>        self.project = project<br>        self.createdAt = .now<br>        self.isCompleted = false<br>    }<br>}</pre><pre>@Model<br>final class Project {<br>    var id = UUID()<br>    var name: String<br>    var tasks: [Task] = []<br>}</pre><pre>@Model<br>final class Tag {<br>    var name: String<br>    var tasks: [Task] = []<br>}</pre><pre>// Querying (SwiftUI + SwiftData)<br>@Query(filter: #Predicate&lt;Task&gt; { !$0.isCompleted },<br>       sort: \.createdAt, order: .forward)<br>var pendingTasks: [Task]</pre><h4>Core Data (Objective-C)</h4><pre>NSManagedObjectContext *context = ...;<br>NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@&quot;Task&quot;];<br>NSArray *results = [context executeFetchRequest:request error:nil];</pre><h4>Bonus: Use with CloudKit</h4><p>If you want to <strong>sync SwiftData or Core Data with iCloud</strong>, you can use:</p><ul><li>NSPersistentCloudKitContainer for Core Data</li><li>CloudKit sync for SwiftData (coming soon / limited currently)</li></ul><p>This lets your data <strong>sync across iPhones, iPads, and Macs</strong> with zero backend.</p><h3>⚙️ 2. Tiny Settings &amp; Flags → UserDefaults</h3><p>UserDefaults is your go-to for <strong>lightweight persistence</strong> of user settings. Think of it as the app&#39;s internal INI file or a tiny key–value registry. It’s incredibly convenient — and also very easy to misuse.</p><blockquote><strong><em>Use it for things like “Did the user complete onboarding?” or “Is dark mode enabled?”</em></strong><em><br> </em><strong><em>Don’t use it to store a whole list of 100 favorite items or a megabyte of JSON.</em></strong></blockquote><h4>✅ Best for</h4><ul><li><strong>Booleans and simple flags</strong><br> e.g. hasOnboarded, isPremiumUser, showWelcomeScreen</li><li><strong>Short strings and identifiers</strong><br> e.g. lastOpenedTab, selectedTheme, preferredLanguage</li><li><strong>Numeric values and timestamps</strong><br> e.g. launchCount, lastSyncDate, volumeLevel</li><li><strong>Raw-value enums</strong><br> Store via enum.rawValue and retrieve with init(rawValue:)</li><li><strong>A/B testing snapshots or LaunchDarkly flags (read-only)</strong><br> For caching last-known flag values on cold start</li><li><strong>User experience tracking</strong><br> e.g. didSeeBetaBanner, didDismissTooltip_v3</li><li><strong>App preferences and lightweight settings</strong><br> e.g. enableCrashReporting, autoSaveEnabled</li><li><strong>Timestamp markers</strong><br> To avoid repeating an operation too frequently (lastBackgroundFetchTime)</li></ul><h4>❌ Avoid for:</h4><ul><li>Arrays of dictionaries or models → prefer <strong>SwiftData</strong></li><li>Images, binary blobs → use <strong>FileManager</strong></li><li>Secrets (tokens, passwords) → use <strong>Keychain</strong></li><li>Realtime updated shared config → prefer a <strong>singleton or a reactive wrapper</strong></li></ul><h4>🧪 Code Examples</h4><h4>Swift (Classic)</h4><pre>UserDefaults.standard.set(true, forKey: &quot;hasOnboarded&quot;)<br>let hasOnboarded = UserDefaults.standard.bool(forKey: &quot;hasOnboarded&quot;)</pre><h4>SwiftUI (Modern)</h4><pre>@AppStorage(&quot;hasOnboarded&quot;) var hasOnboarded = false<br>var body: some View {<br>    if hasOnboarded {<br>        MainAppView()<br>    } else {<br>        OnboardingView()<br>    }<br>}</pre><blockquote><em>@AppStorage auto-syncs your SwiftUI view with changes in UserDefaults — </em><strong><em>no boilerplate binding required.</em></strong></blockquote><h4>Objective-C</h4><pre>[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@&quot;hasOnboarded&quot;];<br>BOOL done = [[NSUserDefaults standardUserDefaults] boolForKey:@&quot;hasOnboarded&quot;];</pre><h4>📦 Namespacing &amp; Safety with Property Wrappers</h4><p>Hardcoding keys like &quot;hasOnboarded&quot; everywhere = brittle. Let’s use a wrapper:</p><pre>@propertyWrapper<br>struct UDFlag&lt;T&gt; {<br>    let key: String<br>    let defaultValue: T<br>    var wrappedValue: T {<br>        get {<br>            UserDefaults.standard.object(forKey: key) as? T ?? defaultValue<br>        }<br>        set {<br>            UserDefaults.standard.set(newValue, forKey: key)<br>        }<br>    }<br>}<br>struct AppPrefs {<br>    @UDFlag(key: &quot;hasOnboarded&quot;, defaultValue: false)<br>    static var hasOnboarded: Bool<br>}</pre><p>Then use it like:</p><pre>if AppPrefs.hasOnboarded {<br>    // show main UI<br>}</pre><h4>🔄 KVO &amp; Change Observation</h4><p>UserDefaults supports <strong>notification-based updates</strong>:</p><pre>NotificationCenter.default.addObserver(<br>    forName: UserDefaults.didChangeNotification,<br>    object: nil,<br>    queue: .main<br>) { _ in<br>    print(&quot;Defaults changed&quot;)<br>}</pre><p>Or use Combine:</p><pre>UserDefaults.standard.publisher(for: \.isDarkMode)<br>    .sink { print(&quot;Dark mode updated: \($0)&quot;) }</pre><h4>👥 Shared Defaults with App Groups</h4><p>When using <strong>iOS Extensions (Widgets, Watch, etc.)</strong>, you often want <strong>shared defaults</strong>:</p><pre>let sharedDefaults = UserDefaults(suiteName: &quot;group.com.mohsin.appgroup&quot;)!<br>sharedDefaults.set(true, forKey: &quot;showWidget&quot;)</pre><p>Works across:</p><ul><li>Main app</li><li>Widgets</li><li>App Clips</li><li>Intents/SiriKit</li><li>Share extensions</li></ul><h4>🔐 What about security?</h4><ul><li>UserDefaults is <strong>not encrypted</strong> — don’t store:</li><li>JWT tokens</li><li>OAuth refresh tokens</li><li>Sensitive timestamps (e.g., PIN expiry)</li><li>These should go in the <strong>Keychain</strong>, not UserDefaults.</li></ul><h3>🚀 3. Fast, Temporary In-Memory Cache → NSCache</h3><p>NSCache is perfect when you need a fast, in-memory key-value store that auto-purges under memory pressure. Unlike dictionaries, NSCache is thread-safe and doesn’t retain strong references to its values, which helps prevent memory leaks in image-heavy apps.</p><h4>✅ When to Use:</h4><ul><li>Caching images, API results, or view models</li><li>Temporary storage that doesn’t need to persist across app restarts</li><li>Avoiding manual memory eviction</li></ul><h4>❌ When Not to Use:</h4><ul><li>You need persistent storage (like files or UserDefaults)</li><li>You need a queryable or relational data structure</li></ul><h4>📦 Real-World Use Case: SwiftlyImageLoader</h4><blockquote><em>In </em><a href="https://github.com/mohsinbmwm3/SwiftlyImageLoader/tree/main"><em>SwiftlyImageLoader</em></a><em> — a lightweight, concurrency-friendly image loading library I built — </em><em>NSCache is used to store decoded images in memory, giving us </em><strong><em>instant UI rendering</em></strong><em> without redundant decoding or network calls.</em></blockquote><p>Here’s a simplified snippet from the library:</p><pre>final class ImageMemoryCache {<br>    private let cache = NSCache&lt;NSString, UIImage&gt;()<br>    func image(forKey key: String) -&gt; UIImage? {<br>        return cache.object(forKey: key as NSString)<br>    }<br>    func insertImage(_ image: UIImage, forKey key: String) {<br>        cache.setObject(image, forKey: key as NSString)<br>    }<br>    func removeImage(forKey key: String) {<br>        cache.removeObject(forKey: key as NSString)<br>    }<br>    func removeAll() {<br>        cache.removeAllObjects()<br>    }<br>}</pre><p>This approach ensures:</p><ul><li><strong>Fast retrieval</strong> for frequently accessed images</li><li><strong>Automatic memory cleanup</strong> when the system is under pressure</li><li><strong>Zero boilerplate</strong> to manage eviction</li></ul><h4>💡 Pro Tip:</h4><p>Use NSCache in combination with a disk cache if you want a <strong>multi-tier caching system</strong> (as done in SwiftlyImageLoader). Memory cache gives speed, disk cache gives persistence.</p><p>🧵 <strong>Concurrency note</strong>: NSCache is thread-safe, but still keep your access patterns clean.</p><h3>4. Files &amp; Downloads → FileManager</h3><p>If you’re storing <strong>media, documents, or exports/imports</strong>, use FileManager.</p><h4>✅ Best for:</h4><ul><li>Images, videos, audio</li><li>Downloaded files</li><li>Export/import (PDF, JSON backups)</li></ul><h4>❌ Avoid for:</h4><ul><li>Structured data queries (pair with DB instead)</li></ul><p><strong>Swift Example</strong></p><pre>let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!<br>let path = docs.appendingPathComponent(&quot;profile.json&quot;)try JSONEncoder().encode(profile).write(to: path, options: .atomic)<br>let loaded = try JSONDecoder().decode(Profile.self, from: Data(contentsOf: path))</pre><p>📌 Pro Tip: Use File Protection APIs for sensitive files (.completeFileProtection).</p><h3>🔐 5. Secrets &amp; Tokens → Keychain</h3><p>Security matters. <strong>Never store tokens or passwords in UserDefaults.</strong></p><p>Will publish a seperate article over this.</p><p><strong>Swift (simplified)</strong></p><pre>func saveToken(_ token: String) {<br>  let data = token.data(using: .utf8)!<br>  SecItemAdd([kSecClass: kSecClassGenericPassword,<br>              kSecAttrAccount: &quot;authToken&quot;,<br>              kSecValueData: data] as CFDictionary, nil)<br>}</pre><h3>☁️ 6. Cross-Device Sync → CloudKit / iCloud</h3><p>When user data needs to follow them across devices:</p><ul><li><strong>NSUbiquitousKeyValueStore</strong> for small key-value sync</li><li><strong>CloudKit</strong> for structured user data</li><li><strong>NSPersistentCloudKitContainer</strong> for Core Data &lt;-&gt; iCloud sync</li></ul><h3>Choosing Quickly (Mental Model)</h3><ul><li><strong>Need queries/relationships/history?</strong> → SwiftData/Core Data</li><li><strong>Just a flag or small value?</strong> → UserDefaults</li><li><strong>Speed boost, no persistence?</strong> → NSCache</li><li><strong>Big files/blobs?</strong> → FileManager</li><li><strong>Secrets?</strong> → Keychain</li><li><strong>Cross-device sync?</strong> → CloudKit</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=084f6ccf1f9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering iOS Background Modes and Tasks: A Comprehensive Guide]]></title>
            <link>https://mohsinkhan845.medium.com/mastering-ios-background-modes-and-tasks-a-comprehensive-guide-322116db13fd?source=rss-cec377a306a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/322116db13fd</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mohsin Khan]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 19:20:44 GMT</pubDate>
            <atom:updated>2025-04-07T19:20:44.329Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most challenging areas in iOS development is handling tasks that must continue (or at least finish gracefully) when the user leaves the app. Whether you need to download a large file or track user location for navigation purposes, understanding iOS background modes is crucial.</p><p>In this article, we’ll explore <strong>how iOS manages apps in the background</strong>, the different <strong>background modes</strong> you can enable, and two practical examples: <strong>background file downloads</strong> and <strong>location updates</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IoHSk-Sea9TS-FmF" /><figcaption>Photo by <a href="https://unsplash.com/@eutahm?utm_source=medium&amp;utm_medium=referral">Eutah Mizushima</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Background Tasks Matter</h3><p>Modern mobile users expect apps to be “always on,” ready with fresh data, even if they haven’t opened the app recently. Some common use cases:</p><ul><li><strong>Downloading content</strong> (like large media files) while the user does other things.</li><li><strong>Location tracking</strong> for navigation, fitness apps, or reminders.</li><li><strong>Periodic data refresh</strong> (news feeds, social media updates, etc.).</li><li><strong>Heavy processing</strong> (data cleanup, indexing) that shouldn’t block the main thread or user interface.</li></ul><p>However, mobile devices have <strong>limited battery</strong> and system resources. iOS thus enforces <strong>strict rules</strong> on when apps can run in the background and for how long.</p><h3>How iOS Suspends and Wakes Apps</h3><p>When the user presses the Home button or switches to another app, iOS sends the current app to the <strong>background</strong>. Soon after, iOS typically <strong>suspends</strong> the app to conserve resources. That means your code <strong>stops running</strong> unless you have explicitly enabled and justified certain background modes.</p><h4>System Termination vs. User Termination</h4><ul><li><strong>System Termination</strong>: iOS may kill your app to free memory or if it’s been idle in the background too long. But if you have an ongoing background task (e.g., a file download in a background URLSession), iOS may relaunch your app later to give you a chance to finish or handle the result.</li><li><strong>User Termination</strong>: If the user force-quits (swipes the app away in the app switcher), iOS <strong>stops</strong> all background tasks. The user has signaled they want your app fully closed.</li></ul><p>Understanding this distinction is critical when designing background workflows. This might be a little difficult to understand, I have explained this in details in <a href="https://mohsinkhan845.medium.com/how-ios-suspends-and-wakes-apps-understanding-the-app-lifecycle-af56bc763f27">this article</a></p><h3>Common Background Modes and Their Use Cases</h3><p>In <strong>Xcode</strong> &gt; <strong>Signing &amp; Capabilities</strong> &gt; <strong>Background Modes</strong>, you’ll see several checkboxes. Here are some of the most commonly used ones:</p><h4><strong>Background Fetch</strong></h4><ul><li>Allows iOS to <strong>wake your app periodically</strong> to fetch new data.</li><li>Perfect for apps that need to stay up to date with minimal user intervention.</li></ul><h4><strong>Background Processing</strong></h4><ul><li>Uses the <strong>BGTasks</strong> framework to schedule longer-running tasks when the system decides it’s a good time (e.g., plugged in, on Wi-Fi).</li><li>Good for large data processing, cleaning databases, etc.</li></ul><h4><strong>Remote Notifications</strong></h4><ul><li>Allows receiving <strong>silent push notifications</strong> to update content in the background.</li><li>Ideal for real-time messaging or content updates triggered by server events.</li></ul><h4><strong>Location Updates</strong></h4><ul><li>Continuously receive location changes or significant-change updates.</li><li>Suitable for fitness, navigation, or location-based reminders.</li></ul><h4><strong>Audio, AirPlay, and Picture in Picture</strong></h4><ul><li>Keep playing audio or video while in the background or with Picture in Picture mode.</li><li>Essential for media apps (e.g., music players).</li></ul><blockquote><strong><em>Tip</em></strong><em>: Only enable the modes you </em><strong><em>truly need</em></strong><em>, because Apple is strict about background usage for performance and battery reasons.</em></blockquote><p>Now lets dive into some examples…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ihh1Lq3QPAqv0rsR" /><figcaption>Photo by <a href="https://unsplash.com/@100pingissues?utm_source=medium&amp;utm_medium=referral">Kaung Myat Min</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Example 1: Background File Download</h3><p>Many apps need to fetch large files in the background. Let’s examine how to do this <strong>reliably</strong> with URLSessionConfiguration.background:</p><p><strong>Enable “Background fetch”</strong> in Xcode capabilities. This alerts iOS that the app may do some networking when in the background.</p><p><strong>Create a Background Session</strong> in your code:</p><pre>let config = URLSessionConfiguration.background(withIdentifier: &quot;com.example.myapp.download&quot;) <br>let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)</pre><p><strong>Start the Download</strong>:</p><pre>if let url = URL(string: &quot;https://example.com/largefile.zip&quot;) {     <br>  let task = session.downloadTask(with: url)     <br>  task.resume() <br>}</pre><p><strong>Handle Delegate Callbacks</strong>:</p><ul><li>didWriteData to track download progress.</li><li>didFinishDownloadingTo to move the file from a temporary location to a permanent folder.</li></ul><h4>Minimizing or Suspending the App</h4><ul><li>If the user leaves the app, iOS continues the download in the background.</li><li>If the system terminates the app but the download isn’t finished, iOS may <strong>relaunch</strong> your app in the background once the download completes, so you can handle the final file.</li></ul><h4>What if the Download Fails Midway?</h4><ul><li>The delegate’s didCompleteWithError might provide <strong>resume data</strong>, letting you create a <strong>new</strong> download task that picks up where you left off. This prevents starting over from zero for large files.</li></ul><p><strong>Key Benefit</strong>: Users don’t have to keep your app open just to download large files.</p><h3>Example 2: Background Location Updates</h3><p>Let’s say you’re building a fitness or navigation app that needs to track user location even when they’re not actively using it:</p><ol><li><strong>Enable “Location updates”</strong> in Xcode capabilities.</li></ol><p><strong>2. Configure CLLocationManager</strong> for background tracking:</p><pre>let locationManager = CLLocationManager() <br>locationManager.requestAlwaysAuthorization() <br>locationManager.allowsBackgroundLocationUpdates = true <br>locationManager.startUpdatingLocation()</pre><p><strong>3. Info.plist Keys</strong></p><ul><li>Add NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription, depending on your approach.</li><li>If you need continuous updates in the background, you’ll typically use <strong>Always</strong> permission.</li></ul><h4>Battery Considerations</h4><ul><li><strong>Continuous GPS</strong> can rapidly drain battery. If precise location is not essential at all times, consider <strong>significant-change</strong> location updates (which wake the app only when the user moves a notable distance) or <strong>region monitoring</strong> (which triggers events upon entering/exiting a region).</li></ul><h4>Minimizing or Suspending the App</h4><ul><li>Even if the user locks the phone or switches apps, iOS continues to deliver location updates if you’ve enabled background location.</li><li>If the user force-quits, those updates stop entirely.</li></ul><h3>Which Background Mode to Use When</h3><ul><li><strong>Short, Periodic Data Fetches</strong>: Use <strong>Background Fetch (#3)</strong>.</li><li><strong>Long-Running Processing</strong>: Use <strong>Background Processing (#4)</strong> via BGTasks for large jobs.</li><li><strong>Continuous Location</strong>: Use <strong>Location Updates (#6)</strong> with CLLocationManager.</li><li><strong>Large File Downloads</strong>: Use a <strong>background URLSession</strong> (plus “Background fetch” for entitlements).</li><li><strong>Instant Server Updates</strong>: Use <strong>Remote Notifications</strong> with silent pushes to wake the app promptly.</li><li><strong>Audio in Background</strong>: Use the <strong>Audio</strong> background mode, ensuring you handle audio sessions properly.</li></ul><p>The key is to enable <strong>only</strong> the modes that align with your app’s functionality. Over-enabling modes can lead to performance issues or App Store review rejections.</p><h3>Best Practices</h3><p><strong>Limit Battery Drain</strong></p><ul><li>Rely on iOS scheduling. Avoid constantly pinging the network. Use waitsForConnectivity = true to pause tasks until the network is available.</li></ul><p><strong>Respect Data Constraints</strong></p><ul><li>For large downloads, consider restricting to Wi-Fi (config.allowsCellularAccess = false) or letting the user decide.</li></ul><p><strong>Graceful Failure Handling</strong></p><ul><li>If network is lost mid-task, store partial progress. Let the user pause/resume.</li></ul><p><strong>Thorough Testing on Real Devices</strong></p><ul><li>The Simulator can’t fully mimic network changes or real GPS movements. Use TestFlight or direct installs to confirm your background logic.</li></ul><p><strong>Clear Justification</strong></p><ul><li>Apple requires you to explain why your app needs background capabilities. Frame it in terms of <strong>user benefit</strong> (navigation, fitness tracking, up-to-date data, etc.).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k99qgqoUb6QCcqsN" /><figcaption>Photo by <a href="https://unsplash.com/@karlahrnndz?utm_source=medium&amp;utm_medium=referral">Karla Hernandez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Putting It All Together</h3><p>iOS background modes are a <strong>powerful</strong> tool set. They let you extend your app’s functionality beyond the foreground, delivering a smooth user experience without forcing people to keep your app open.</p><ul><li><strong>Understanding iOS Lifecycle</strong>: iOS suspends and wakes apps based on resource constraints and user actions.</li><li><strong>Choosing the Right Mode</strong>: Match your feature (downloading, location, scheduling) to the corresponding background mode.</li><li><strong>Implementing Carefully</strong>: Use the relevant frameworks (URLSessionConfiguration.background, CLLocationManager, BGTasks) and test thoroughly on real hardware.</li><li><strong>Staying Battery-Friendly</strong>: Do just enough background work to serve your users without draining the device or hogging system resources.</li></ul><p>By following these guidelines, you can create a <strong>robust</strong>, <strong>user-friendly</strong> app that continues working seamlessly even after the user navigates away.</p><h3>Conclusion</h3><p>Whether you’re building a navigation app, a music player, or a data-rich social platform, background tasks can <strong>elevate</strong> the user experience. Smart use of iOS background modes — combined with careful attention to battery, data usage, and system constraints — will ensure your app feels both <strong>responsive</strong> and <strong>efficient</strong>.</p><p>If you found this overview helpful, consider sharing it with your fellow iOS devs. Feel free to leave a comment below with your own tips or background-mode success stories!</p><blockquote>Thanks for reading! Stay tuned for more deep dives into iOS internals, performance optimizations, and best practices.</blockquote><h4>Further Reading</h4><ul><li>Apple Documentation on <a href="https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle">Background Execution</a></li><li><a href="https://developer.apple.com/documentation/backgroundtasks">BGTasks Framework</a></li><li><a href="https://developer.apple.com/documentation/foundation/url_loading_system/downloading_files_in_the_background">URLSession Background Transfers</a></li><li><a href="https://developer.apple.com/documentation/corelocation">Location and Maps Programming Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=322116db13fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How iOS Suspends and Wakes Apps: Understanding the App Lifecycle]]></title>
            <link>https://mohsinkhan845.medium.com/how-ios-suspends-and-wakes-apps-understanding-the-app-lifecycle-af56bc763f27?source=rss-cec377a306a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/af56bc763f27</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[programming-tips]]></category>
            <dc:creator><![CDATA[Mohsin Khan]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 19:18:02 GMT</pubDate>
            <atom:updated>2025-04-07T19:18:02.175Z</atom:updated>
            <content:encoded><![CDATA[<p>iOS devices have limited resources like CPU, memory, and battery, so the system manages running apps aggressively to preserve performance. If you want your app to work well in real-world situations — especially when users leave it, lock their phones, or if the OS itself needs more memory — you need to master how iOS suspends and wakes apps.</p><p>This article is a deep dive into:</p><ol><li>The <strong>iOS app lifecycle</strong> states (inactive, background, suspended, terminated).</li><li><strong>Common scenarios</strong> when apps are sent to the background.</li><li>How and <strong>why</strong> iOS might kill your app — and what you can do about it.</li><li><strong>Real examples</strong> of app relaunches in the background.</li></ol><h3>iOS App Lifecycle at a Glance</h3><p>iOS manages apps through distinct lifecycle states. Here’s a simplified overview:</p><ol><li><strong>Not Running</strong> — The app isn’t in memory at all.</li><li><strong>Inactive</strong> — The app is in the foreground but not receiving events (e.g., an incoming call overlay).</li><li><strong>Active</strong> — The app is in the foreground and receiving user events (the normal running state).</li><li><strong>Background</strong> — The app is executing code in the background (briefly) or performing tasks declared under background modes.</li><li><strong>Suspended</strong> — The app is in memory but not actively executing code. iOS “freezes” the app state to save resources.</li><li><strong>Terminated</strong> — iOS has removed the app from memory. The app can be relaunched as needed.</li></ol><blockquote><em>In day-to-day usage, the main transitions you’ll see are from </em><strong><em>Active</em></strong><em> to </em><strong><em>Background</em></strong><em> and eventually to </em><strong><em>Suspended</em></strong><em> or </em><strong><em>Terminated</em></strong><em>.</em></blockquote><h3>When Does iOS Send Apps to the Background?</h3><h4>Scenario A: User Presses Home or Switches to Another App</h4><ul><li><strong>Transition</strong>: Active → Background (briefly) → Suspended</li><li><strong>Why?</strong>: Once a user leaves your app, iOS immediately calls applicationDidEnterBackground(_:) (in UIKit life cycle) or the analogous SwiftUI/SceneDelegate method. Your app gets a short window (usually a few seconds) to do last-minute tasks—like saving data—before iOS suspends it.</li></ul><h4>Scenario B: User Locks the Phone</h4><ul><li><strong>Transition</strong>: Active → Background → Suspended</li><li><strong>Why?</strong>: The screen turns off, so iOS places your app in the background state. After a brief time, it suspends the app to save battery.</li></ul><h4>Scenario C: App Minimizes Itself Programmatically</h4><ul><li>In most cases, an app doesn’t voluntarily minimize, but it can trigger background tasks (like a phone call screen or external URL scheme). The OS typically handles the actual background transition.</li></ul><p><strong>Key Takeaway</strong>: Under normal usage (like pressing Home or locking the screen), your app moves to <strong>Background</strong> first, then iOS swiftly suspends it unless you have an active background mode (e.g., playing audio, location tracking).</p><h3>Suspended vs. Terminated</h3><p>Once your app enters the <strong>Suspended</strong> state, iOS keeps it in memory but does not let it run code. This means:</p><ul><li><strong>No CPU time</strong> is used.</li><li>Your app remains in memory, so if the user switches back quickly, it resumes from where it left off.</li></ul><p>However, if iOS needs memory or if too many apps are suspended:</p><ul><li><strong>System Termination</strong>: iOS <strong>kills</strong> your suspended app to free up RAM. From your app’s perspective, it’s the same as being forcibly shut down. You get no direct callback about this event.</li><li><strong>User Termination</strong>: If the user opens the app switcher and swipes away your app, that also terminates it. In this scenario, iOS assumes the user wants the app fully shut down — any ongoing tasks are halted.</li></ul><h3>Waking the App: Common Scenarios</h3><p><strong>“Waking”</strong> an app means iOS actively moves the app from either <strong>Not Running</strong> or <strong>Suspended</strong> (or even from <strong>Background</strong> if it’s in the middle of a short background task) back into <strong>Active</strong> or a reawakened <strong>Background</strong> state. Here are some ways that can happen:</p><h4>Scenario A: User Relaunches the App</h4><ul><li>If your app was still suspended in memory, iOS moves it to the foreground <strong>instantly</strong>, picking up at the last screen.</li><li>If it was terminated, iOS loads it from scratch, calling didFinishLaunchingWithOptions (or SwiftUI’s @main struct).</li></ul><h4>Scenario B: Background Tasks or Events</h4><ul><li><strong>Background Fetch</strong>: iOS periodically wakes apps that have background fetch enabled.</li><li><strong>Remote Notifications</strong> (Silent Push): iOS wakes your app to process a push payload.</li><li><strong>Location Updates</strong>: If you have background location enabled, iOS can resume your app in the background to deliver location events.</li><li><strong>Background URLSession</strong>: If a download finishes in a background URL session after the app is terminated, iOS relaunches your app in the background to handle the delegate callbacks.</li></ul><h4>Scenario C: System Re-launch for Terminated Apps</h4><ul><li>Let’s say your app was downloading a file in the background, but iOS killed it due to memory pressure. If the download completes eventually, iOS can <strong>relaunch</strong> your app in the background (using handleEventsForBackgroundURLSession) so you can finalize the transfer.</li></ul><h3>Real Example: Minimizing &amp; Coming Back</h3><p>Let’s walk through a <strong>simple example</strong> to make this more concrete:</p><ol><li><strong>User opens your app</strong> → The app is <strong>Active</strong>.</li><li><strong>User presses Home</strong> → iOS moves the app to <strong>Background</strong>.</li></ol><ul><li>applicationDidEnterBackground(_:) is called.</li></ul><ol><li><strong>A few seconds later</strong> → The app transitions to <strong>Suspended</strong>.</li><li><strong>User returns quickly</strong> (from the Home screen) → The app transitions from <strong>Suspended</strong> back to <strong>Active</strong>, instantly showing where they left off.</li><li><strong>User is done</strong> and doesn’t open the app for hours → iOS might eventually <strong>Terminate</strong> it, especially if memory is needed for other apps.</li><li><strong>User taps the app icon</strong> next day → The app is launched fresh from scratch (Not Running → Active), calling your standard launch methods.</li></ol><h3>Advanced Example: System-Killed During a Background Task</h3><ol><li><strong>User starts downloading a file</strong> using a <strong>background URL session</strong>.</li><li><strong>User locks the phone</strong> or switches apps → The system moves your app to the background.</li><li><strong>iOS memory pressure</strong> → iOS kills your suspended app, but the download continues because the background URL session is managed by the system daemon.</li><li><strong>Download finishes</strong> → iOS <strong>relaunches</strong> your app in the background to handle the delegate’s didFinishDownloadingTo callback.</li><li>Your app runs just long enough to process the file, then goes back to a suspended state, or iOS kills it again if no foreground activity is needed.</li></ol><h3>How to Ensure a Smooth Background Experience</h3><p><strong>AppDelegate / SceneDelegate Methods</strong></p><ul><li>Use applicationDidEnterBackground(_:) or SwiftUI scene’s sceneDidEnterBackground(_:) to save state quickly.</li><li>Use applicationWillTerminate(_:) for last-chance cleanup (but note that it’s not always called if the system kills your app).</li></ul><p><strong>Background Modes</strong></p><ul><li>Only enable relevant modes: e.g., Audio for background music, Location for ongoing GPS tracking, Background Fetch for periodic data updates, etc.</li><li>This keeps iOS from prematurely suspending your app, and also justifies to Apple why you need to run in the background.</li></ul><p><strong>Testing on Real Devices</strong></p><ul><li>Simulator background behavior can differ from physical devices. Test actual lock/wake cycles, memory pressure, force-quits, and network changes on a real phone or iPad.</li></ul><p><strong>Minimal Use of Background Resources</strong></p><ul><li>iOS heavily optimizes battery usage. If your background tasks are too frequent or resource-heavy, iOS might throttle or kill your app more aggressively.</li><li>Design background tasks to be short, efficient, and triggered only when needed.</li></ul><h3>Summary &amp; Key Takeaways</h3><ul><li><strong>Suspended</strong> is not the same as <strong>Terminated</strong>. In Suspended, the app is still in memory but not running code.</li><li>iOS can <strong>wake</strong> or <strong>kill</strong> the app in the background at its discretion — particularly if the app has an active background task or the OS needs resources.</li><li><strong>User force-quit</strong> overrides system attempts to keep your app alive (e.g., background tasks stop).</li><li>With the right <strong>background mode</strong> entitlements, iOS will <strong>relaunch</strong> your app in certain scenarios (finishing downloads, delivering location updates, etc.).</li><li>Always <strong>test</strong> real user flows on physical devices to confirm how your app behaves under different states (minimized, locked, memory pressure, etc.).</li></ul><p>Understanding these details allows you to design robust background features — like location tracking, silent push notifications, or background file transfers — without surprising your users or burning through their battery. Properly handling suspension, termination, and reawakening is key to an app that feels effortless and responsive in everyday use.</p><h3>Thanks for Reading!</h3><p>If you found this deep dive helpful, please <strong>clap</strong> or share with friends. Also, check out my related articles on <a href="https://developer.apple.com/documentation/xcode/configuring-background-execution-modes">iOS background modes</a> and best practices for <a href="https://developer.apple.com/documentation/foundation/downloading-files-in-the-background?language=objc">background URL sessions</a>.</p><p>Feel free to leave a comment or question below! How do you handle app suspension and wakeups in your projects?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af56bc763f27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should use MVVM for iOS Development?]]></title>
            <link>https://mohsinkhan845.medium.com/why-you-should-use-mvvm-for-ios-development-cb7845677a06?source=rss-cec377a306a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb7845677a06</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Mohsin Khan]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 10:54:45 GMT</pubDate>
            <atom:updated>2024-12-16T11:23:14.758Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2EIew6WnZVRzUN9E" /><figcaption>Photo by <a href="https://unsplash.com/@soymeraki?utm_source=medium&amp;utm_medium=referral">Javier Allegue Barros</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Feeling overwhelmed by implementing MVC in iOS? Confused about whether MVVM is the better choice?</p><p>If these questions resonate with you, you’re in the right place. Keep reading to unravel the mysteries of iOS architectural patterns. By the end of this article, you’ll have a clearer understanding of these patterns. If not, feel free to share your thoughts in the comments.</p><p>This guide will help you sharpen your knowledge of iOS design patterns by exploring some of the most popular ones. Stay tuned as we navigate through these challenges and uncover the nuances of iOS app architecture.</p><p>💻 <strong>Discover More MVVM Examples</strong>: Explore a variety of MVVM code samples, including additional scenarios not covered in this article, on my GitHub repository: <a href="https://github.com/mohsinbmwm3/mvvm-code-samples">MVVM Code Samples</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DT29ZGsMjCV6gn4I" /><figcaption>Photo by <a href="https://unsplash.com/@nofilter_noglory?utm_source=medium&amp;utm_medium=referral">Tim Goedhart</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Care About Choosing the Architecture?</h3><p>In iOS development, each architectural layer addresses specific types of problems, often leveraging particular frameworks or tools. To effectively understand how these layers work together, it’s helpful to explore them layer by layer. However, you don’t need to dive into the intricate details of every layer to understand its purpose; each layer abstracts the complexities of those below it.</p><p>Take the UI layer, for instance. In an MVVM or VIPER architecture, this layer focuses on presenting information to the user and handling their interactions. It doesn’t concern itself with how the underlying business logic works — that’s handled by another layer. For example:</p><pre>// ViewModel in MVVM (UI Layer)<br>class OrderViewModel: ObservableObject {<br>  @Published var totalPrice: String = &quot;&quot;<br>  @Published var deliveryDate: String = &quot;&quot;<br>  <br>  private let orderService: OrderService<br>  init(orderService: OrderService) {<br>      self.orderService = orderService<br>  }<br>  <br>  func fetchOrderDetails(for customer: String, items: [String: Int]) {<br>      let result = orderService.calculateOrder(customer: customer, items: items)<br>      totalPrice = &quot;\(result.price) USD&quot;<br>      deliveryDate = result.deliveryDate<br>  }<br>}<br>// OrderService in Business Logic Layer<br>class OrderService {<br>    func calculateOrder(customer: String, items: [String: Int]) -&gt; (price: Double, deliveryDate: String) {<br>        // Simplified logic for demonstration<br>        let total = items.reduce(0) { $0 + Double($1.value) * 10 }<br>        let deliveryDate = &quot;16th September&quot;<br>        return (price: total, deliveryDate: deliveryDate)<br>    }<br>}<br>// Example Usage in SwiftUI View<br>struct OrderView: View {<br>    @StateObject var viewModel = OrderViewModel(orderService: OrderService())<br>    var body: some View {<br>        VStack {<br>            Text(&quot;Total Price: \(viewModel.totalPrice)&quot;)<br>            Text(&quot;Delivery Date: \(viewModel.deliveryDate)&quot;)<br>        }<br>        .onAppear {<br>            viewModel.fetchOrderDetails(for: &quot;Customer X&quot;, items: [&quot;Widget&quot;: 5, &quot;Zettul&quot;: 3])<br>        }<br>    }<br>}</pre><p>Here, the UI layer (View and ViewModel) focuses on displaying the total price and delivery date, while the business logic layer (OrderService) handles the core calculations, such as applying discounts or determining stock availability. The UI layer simply asks the business logic layer for the information it needs and displays the results.</p><p>This separation of concerns raises an important question: why divide responsibilities into layers? Here are a few reasons:</p><ol><li><strong>Reusability</strong>: The business logic can be reused across different UIs, such as a SwiftUI app and a backend API.</li><li><strong>Legacy Code</strong>: Business logic might already exist from a previous implementation, making it easier to integrate without rewriting it.</li><li><strong>Cognitive Load</strong>: Splitting responsibilities helps developers focus on one layer at a time, avoiding the mental overload of tackling UI and business logic simultaneously.</li><li><strong>Team Collaboration</strong>: Different teams with specialized skills (e.g., UI/UX designers and backend engineers) can work independently on their respective layers.</li></ol><p>This thinking extends to other layers, such as data persistence. For example:</p><pre>// Persistence Layer<br>class OrderRepository {<br>    func saveOrder(_ order: Order) {<br>        // Save order to local database<br>    }<br>    <br>    func fetchOrder(by id: String) -&gt; Order? {<br>        // Retrieve order from database<br>        return nil<br>    }<br>}<br>// Example Usage in Business Logic Layer<br>class OrderService {<br>    private let repository: OrderRepository<br>    init(repository: OrderRepository) {<br>        self.repository = repository<br>    }<br>    func calculateOrder(customer: String, items: [String: Int]) -&gt; (price: Double, deliveryDate: String) {<br>        // Business logic using repository<br>        repository.saveOrder(Order(id: &quot;123&quot;, customer: customer, items: items))<br>        return (price: 450, deliveryDate: &quot;16th September&quot;)<br>    }<br>}</pre><blockquote>When working with layers, treat each one as a black box, focusing only on its role while abstracting away the details of others. This modular approach allows for easier debugging, testing, and scaling as your app grows. For further learning, start with a single layer — such as UI, business logic, or persistence — and dive deeper into its implementation. Then, ask specific questions if you get stuck.</blockquote><p>Choosing the right architecture ensures your codebase remains clean, maintainable, and scalable for the long term.</p><h3>Defining the Features of a Good Architecture</h3><p>A solid architecture follow to principles that promote clarity, maintainability, and efficiency. Few key features based on timeless principles, including insights from Uncle Bob’s <em>Clean Architecture</em>:</p><h4>1. Separation of Responsibilities</h4><ul><li>Responsibilities should be distributed among entities with well-defined and strict roles, adhering to the <em>Single Responsibility Principle (SRP)</em>.</li><li>This ensures that each module or class focuses on one task, making it easier to understand, maintain, and extend.</li></ul><h4>2. Testability</h4><ul><li>A good architecture facilitates unit testing by design, making it easier to identify and fix issues early.</li><li>When responsibilities are clearly separated, each component can be tested in isolation, reducing the risk of runtime errors after new features or refactoring.</li></ul><h4>3. Maintainability and Simplicity</h4><ul><li>An architecture should aim for minimal code complexity, as simpler code is easier to maintain and debug.</li><li>Following the <em>KISS (Keep It Simple, Stupid)</em> principle ensures that the system avoids unnecessary complexity.</li></ul><h4>Why Separation Matters</h4><p>Separation of responsibilities prevents overwhelming cognitive load by dividing complex systems into manageable pieces. While experience helps developers handle complexity, cognitive ability doesn’t scale indefinitely. By distributing responsibilities effectively, we can focus on solving smaller, specific problems within each entity.</p><h4>Why Testability Matters</h4><p>Developers who rely on unit tests understand their value — they catch issues during development, saving time and preventing errors from reaching users. Tests that break during refactoring or feature additions act as a safety net, ensuring confidence in code changes.</p><h4>Why Simplicity Matters</h4><p>As Uncle Bob says, “The best code is no code at all.” Writing less code reduces the chances of bugs and lowers maintenance costs. While clever solutions may seem appealing, simplicity should always take precedence, balancing efficiency with long-term manageability.</p><p>By following these principles, you create an architecture that is not only robust and scalable but also easier to work with over time.</p><h3>Understanding MVVM in iOS: Bridging Data and UI with Elegance</h3><p>The MVVM (Model-View-ViewModel) pattern in iOS organizes the interaction between data (Model) and UI (View) by emphasizing separation of concerns. The ViewModel acts as a bridge, handling presentation logic to ensure the UI reflects the system’s state while keeping the Model focused on raw data and business rules.</p><p>Here’s an example:</p><ul><li>A <strong>ViewModel</strong> might hold properties like userName, email, or isFormValid.</li><li>The View observes these properties, updating UI components like labels, text fields, or buttons when changes occur.</li></ul><h4>How Does It Work in Practice?</h4><p>Imagine a user registration screen. Initially, the ViewModel’s properties are empty or in an “incomplete” state, so the Submit button is disabled:</p><pre>// ViewModel<br>class RegistrationViewModel: ObservableObject {<br>    @Published var email: String = &quot;&quot;<br>    @Published var password: String = &quot;&quot;<br>    @Published var isFormValid: Bool = false<br>    <br>    private let emailValidator = EmailValidator()<br>    private let passwordValidator = PasswordValidator()<br><br>    func validate() {<br>        isFormValid = emailValidator.isValid(email) &amp;&amp; passwordValidator.isValid(password)<br>    }<br>}<br>// Validator Example<br>class EmailValidator {<br>    func isValid(_ email: String) -&gt; Bool {<br>        return email.contains(&quot;@&quot;) // Simplified for demo<br>    }<br>}<br>// View<br>struct RegistrationView: View {<br>    @StateObject var viewModel = RegistrationViewModel()<br>    var body: some View {<br>        VStack {<br>            TextField(&quot;Email&quot;, text: $viewModel.email)<br>                .onChange(of: viewModel.email) { _ in viewModel.validate() }<br>            TextField(&quot;Password&quot;, text: $viewModel.password)<br>                .onChange(of: viewModel.password) { _ in viewModel.validate() }<br>            Button(&quot;Submit&quot;) {<br>                // Submit action<br>            }<br>            .disabled(!viewModel.isFormValid)<br>        }<br>    }<br>}</pre><p>In this flow:</p><ol><li>The user enters their email and password.</li><li>Validators in the ViewModel check for correctness (e.g., “Is this a valid email format?”).</li><li>The View reflects these validations (e.g., enabling/disabling the Submit button or showing an error message).</li></ol><p>This creates a clean separation where:</p><ul><li>The <strong>ViewModel</strong> ensures the View gets only the data it needs.</li><li>The <strong>View</strong> reacts automatically without directly handling validation or logic.</li></ul><p>🔗 <strong>Looking for More Examples?</strong> Find additional MVVM implementations and ideas to enhance your understanding on my GitHub repository: <a href="https://github.com/mohsinbmwm3/mvvm-code-samples">MVVM Code Samples</a>.</p><h4>Advantages of MVVM</h4><ul><li><strong>Clear Separation of Concerns</strong>: The View handles UI, the ViewModel manages presentation logic, and the Model focuses on data, reducing code interdependence.</li><li><strong>Enhanced Testability</strong>: The ViewModel is easy to unit test since it operates independently of the UI framework.</li><li><strong>Improved Code Reusability</strong>: ViewModels can be reused across multiple views or platforms, promoting modular design.</li><li><strong>Reactive Updates</strong>: With bindings (e.g., @Published in SwiftUI), UI components automatically reflect data changes, minimizing manual synchronization.</li><li><strong>Simplified UI Logic</strong>: By offloading complex UI logic to the ViewModel, Views become lightweight and focused purely on presentation.</li></ul><h4>Challenges of MVVM</h4><h3>Challenges of MVVM in iOS</h3><ol><li><strong>Dual Maintenance Overhead</strong>: Managing both the Model and ViewModel can lead to redundancy, especially in simple screens where this abstraction feels unnecessary.</li><li><strong>Complex State Management</strong>: Handling edge cases, like partial form states or asynchronous updates, can make ViewModels bloated and harder to maintain.</li><li><strong>Unintended Tight Coupling</strong>: Overuse of bindings can unintentionally couple the View and ViewModel, making changes ripple across layers.</li><li><strong>Debugging Reactive Chains</strong>: Tracking down issues in a complex reactive setup (e.g., Combine or RxSwift) can be challenging, as multiple bindings can obscure the source of a bug.</li><li><strong>Performance Pitfalls</strong>: In large-scale apps, excessive property observations or frequent updates in ViewModels can lead to performance bottlenecks, especially when rendering complex views.</li></ol><h4>Philosophical Foundations: Simplicity and Clarity</h4><p>As Uncle Bob states, <em>“The art of programming is managing complexity.”</em> MVVM takes care of this philosophy by dividing responsibilities into manageable layers, making systems easier to understand, modify, and extend. It embraces the <strong>Open-Closed Principle</strong>, allowing you to extend the ViewModel with new features without modifying existing logic.</p><p>However, MVVM also teaches us a deeper truth: simplicity is not the absence of complexity but the mastery of it. By creating clear roles for the Model, ViewModel, and View, we reduce the chaotic interdependence of components. This approach aligns with the broader principle that well-designed systems reflect the clarity of thought behind them.</p><h4>Balancing Practicality and Ideals</h4><p>While MVVM is powerful, it’s not a silver bullet. Philosophically, it urges us to seek balance:</p><ul><li>Use <strong>ViewModels</strong> where they add clarity but avoid overengineering for trivial screens.</li><li>Favor simplicity, but not at the cost of sacrificing long-term maintainability.</li></ul><blockquote>In the end, choosing MVVM isn’t just about writing better code — it’s about building systems that are a joy to work with, today and tomorrow. As software developers, this is the architecture we strive for: one that respects the present while preparing for the future.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb7845677a06" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>