<?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 Sachin Sabat on Medium]]></title>
        <description><![CDATA[Stories by Sachin Sabat on Medium]]></description>
        <link>https://medium.com/@sabatsachin?source=rss-fad79356b8fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*E2k2YFIapFKzSQXvK9KPtw.jpeg</url>
            <title>Stories by Sachin Sabat on Medium</title>
            <link>https://medium.com/@sabatsachin?source=rss-fad79356b8fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:39:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sabatsachin/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[iOS application execution states]]></title>
            <link>https://sabatsachin.medium.com/ios-application-execution-states-2aeba3d7c298?source=rss-fad79356b8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aeba3d7c298</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Sachin Sabat]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 15:34:21 GMT</pubDate>
            <atom:updated>2026-09-29T17:46:30.319Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>The UI lifecycle and the process lifecycle are different things, and iOS — not your app — ultimately controls whether your process continues to execute.</em></strong></p><p>That distinction becomes extremely important for timers, persistence, networking, downloads, and background work.</p><h3>1. iOS application execution states</h3><p>There are two related concepts:</p><ol><li><strong>Scene/UI lifecycle</strong> — what state a particular UI scene is in.</li><li><strong>Process lifecycle</strong> — whether the app process is actually executing, suspended, or terminated.</li></ol><p>For modern iOS, UIKit uses the scene-based lifecycle, and SwiftUI exposes essentially the same concept through ScenePhase. Apple documents these as separate per-scene states because an app can have multiple scenes, each in a different state. (<a href="https://developer.apple.com/documentation/uikit/managing-your-app-s-life-cycle?changes=latest_7%2Clatest_7&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><h3>The practical state machine</h3><pre>┌──────────────────┐<br>                    │   NOT RUNNING    │<br>                    └────────┬─────────┘<br>                             │ launch<br>                             ▼<br>                    ┌──────────────────┐<br>                    │    UNATTACHED    │<br>                    └────────┬─────────┘<br>                             │<br>                             ▼<br>                 ┌───────────────────────┐<br>                 │ FOREGROUND INACTIVE   │<br>                 └───────────┬───────────┘<br>                             │<br>                             ▼<br>                 ┌───────────────────────┐<br>                 │   FOREGROUND ACTIVE   │<br>                 └───────────┬───────────┘<br>                             │<br>                      Home / app switch /<br>                      interruption / lock<br>                             │<br>                             ▼<br>                 ┌───────────────────────┐<br>                 │       BACKGROUND      │<br>                 └───────────┬───────────┘<br>                             │<br>                      shortly afterward<br>                             ▼<br>                 ┌───────────────────────┐<br>                 │       SUSPENDED       │<br>                 └───────────┬───────────┘<br>                             │<br>                      memory pressure /<br>                      system termination<br>                             ▼<br>                    ┌──────────────────┐<br>                    │    TERMINATED    │<br>                    └──────────────────┘</pre><p>The exact transitions vary by circumstance. A scene can also be disconnected and become unattached; the process itself may remain alive or later be terminated. (<a href="https://developer.apple.com/documentation/uikit/managing-your-app-s-life-cycle?changes=latest_7%2Clatest_7&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><h3>2. What does each state actually mean?</h3><h3>A. Not Running</h3><p>The application process isn’t currently running.</p><p>There is:</p><ul><li>no executing application code</li><li>no timers firing</li><li>no active Task</li><li>no in-memory Core Data context</li><li>no ordinary network callback being handled by your app</li></ul><p>The app may be launched later by the user or, for certain system-supported background events, by the OS.</p><h3>3. Unattached</h3><p>This is primarily a <strong>scene state</strong>.</p><p>UIKit creates a scene and attaches it to your process. Apple’s scene lifecycle begins with an unattached scene, which can then move toward foreground/background operation. (<a href="https://developer.apple.com/documentation/uikit/managing-your-app-s-life-cycle?changes=latest_7%2Clatest_7&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><p>You don’t usually discuss this state heavily in a normal app interview unless the interviewer asks specifically about multi-window/multi-scene architecture.</p><h3>4. Foreground Inactive</h3><p>The app is still effectively in the foreground, but isn’t currently receiving normal user interaction.</p><p>Examples can include:</p><ul><li>an interruption</li><li>transition between active/inactive</li><li>system UI temporarily appearing</li></ul><p>Apple describes this as a state where the scene is in the foreground but should pause its work. (<a href="https://developer.apple.com/documentation/swiftui/scenephase/active?utm_source=chatgpt.com">Apple Developer</a>)</p><p>Typical actions:</p><pre>Pause:<br>- animations that are expensive<br>- polling<br>- nonessential work<br>- UI interactions requiring active focus</pre><p>But don’t treat inactive as equivalent to &quot;app has disappeared for hours.&quot;</p><h3>5. Foreground Active</h3><p>This is the state where your UI is visible and interactive.</p><p>SwiftUI:</p><pre>@Environment(\.scenePhase) private var scenePhase</pre><p>scenePhase == .active</p><p>Apple defines .active as foreground and interactive. (<a href="https://developer.apple.com/documentation/swiftui/scenephase/active?utm_source=chatgpt.com">Apple Developer</a>)</p><p>This is where it’s appropriate to perform:</p><ul><li>polling</li><li>interactive network calls</li><li>animations</li><li>UI updates</li><li>user-triggered operations</li><li>normal URLSession tasks</li><li>timers</li></ul><h3>6. Background</h3><p>The UI is no longer visible.</p><p>This is <strong>not</strong> equivalent to “my app keeps running in the background.”</p><p>That’s one of the most important interview points.</p><p>Normally:</p><pre>Foreground<br>   ↓<br>Background<br>   ↓<br>System gives app a short period<br>   ↓<br>Suspended</pre><p>Apple explicitly says apps should do as little as possible in the background, and normally an app is suspended shortly afterward. (<a href="https://developer.apple.com/documentation/uikit/preparing-your-ui-to-run-in-the-background?changes=__7_8&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><p>So:</p><pre>Timer.scheduledTimer(...)</pre><p>does <strong>not</strong> mean:</p><blockquote><em>“Run this every 30 seconds forever, even while my app is backgrounded.”</em></blockquote><p>That’s not a valid iOS architecture.</p><h3>7. Suspended</h3><p>This is where many developers misunderstand iOS.</p><p>The app process remains in memory, but <strong>your code is not executing</strong>.</p><p>Conceptually:</p><pre>RAM:<br>    App process     ✅ present</pre><pre>CPU execution:<br>    App code        ❌ not executing</pre><p>So things like:</p><pre>Timer<br>DispatchSourceTimer<br>Task.sleep()<br>DispatchQueue.asyncAfter()<br>RunLoop</pre><p>should <strong>not</strong> be treated as reliable mechanisms for continuing work while the app is suspended.</p><p>This is why background requirements must use an appropriate OS-managed mechanism.</p><p>Apple specifically describes suspension as preventing the app from continuing ordinary execution. (<a href="https://developer.apple.com/documentation/uikit/preparing-your-ui-to-run-in-the-background?changes=__7_8&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><h3>8. Terminated</h3><p>The process is no longer in memory.</p><p>This can happen for reasons such as:</p><ul><li>memory pressure</li><li>crash</li><li>system termination</li><li>user force-quit</li></ul><p>And this is where in-memory data disappears.</p><p>A very important interview statement is:</p><blockquote><strong><em>Never assume that you’ll receive a final callback before termination.</em></strong></blockquote><p>applicationWillTerminate exists, but modern scene-based/background execution means you should not make your data durability depend on it. Apple notes that this callback generally isn&#39;t invoked just because a background-capable app is moved out of the foreground. (<a href="https://developer.apple.com/documentation/uikit/uiapplicationdelegate/applicationwillterminate%28_%3A%29?changes=l_9&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><p>So this architecture is bad:</p><pre>Keep all user changes in memory<br>        ↓<br>Save only in applicationWillTerminate</pre><p>Because termination may occur without giving you a dependable opportunity to save.</p><h3>9. SwiftUI vs UIKit lifecycle</h3><p>The underlying OS lifecycle is the same; the API you observe differs.</p><h3>SwiftUI</h3><p>You commonly use:</p><pre>@Environment(\.scenePhase) private var scenePhase</pre><p>Example:</p><pre>struct ContentView: View {<br>    @Environment(\.scenePhase) private var scenePhase</pre><pre>    var body: some View {<br>        Text(&quot;Hello&quot;)<br>            .onChange(of: scenePhase) { _, phase in<br>                switch phase {<br>                case .active:<br>                    print(&quot;Active&quot;)</pre><pre>                case .inactive:<br>                    print(&quot;Inactive&quot;)</pre><pre>                case .background:<br>                    print(&quot;Background&quot;)</pre><pre>                @unknown default:<br>                    break<br>                }<br>            }<br>    }<br>}</pre><p>Apple explicitly recommends using scenePhase to respond to these transitions. (<a href="https://developer.apple.com/documentation/swiftui/scenephase?changes=_4&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><h3>UIKit</h3><p>You typically deal with UISceneDelegate callbacks such as:</p><pre>sceneWillEnterForeground(_:)<br>sceneDidBecomeActive(_:)<br>sceneWillResignActive(_:)<br>sceneDidEnterBackground(_:)<br>sceneDidDisconnect(_:)</pre><p>Modern UIKit scene lifecycle events are delivered per scene. (<a href="https://developer.apple.com/documentation/uikit/managing-your-app-s-life-cycle?changes=latest_7%2Clatest_7&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><h3>Scenario 1</h3><h3>API + timer + app goes background + returns foreground</h3><p>Suppose you have:</p><pre>GET /orders<br>GET /inventory<br>GET /hotel-prices</pre><p>and you’re doing:</p><pre>Every 30 seconds → API call</pre><h3>Naive implementation</h3><pre>Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { _ in<br>    api.fetchData()<br>}</pre><p>Developer thinks:</p><pre>30 sec<br>30 sec<br>30 sec<br>30 sec<br>     ↓<br>App background<br>     ↓<br>30 sec<br>30 sec<br>30 sec</pre><p>That’s wrong.</p><p>Once iOS suspends your application, your timer doesn’t continue executing reliably.</p><h3>What I would implement</h3><p>I would separate:</p><h3>1. Polling mechanism</h3><p>from</p><h3>2. Data freshness policy</h3><p>This is a much stronger architecture.</p><pre>PollingService<br>     │<br>     ├── start()<br>     ├── stop()<br>     └── refresh()<br>          │<br>          ▼<br>      API Client<br>          │<br>          ▼<br>      Repository<br>          │<br>          ▼<br>      Local Cache / Core Data</pre><p>And lifecycle controls the polling.</p><h3>Step 1 — foreground</h3><p>When app becomes active:</p><pre>startPolling()</pre><p>Example:</p><pre>final class PollingService {<br>    private var task: Task&lt;Void, Never&gt;?</pre><pre>    func start() {<br>        guard task == nil else { return }</pre><pre>        task = Task {<br>            while !Task.isCancelled {<br>                await refresh()</pre><pre>                try? await Task.sleep(for: .seconds(30))<br>            }<br>        }<br>    }</pre><pre>    func stop() {<br>        task?.cancel()<br>        task = nil<br>    }</pre><pre>    private func refresh() async {<br>        // API call<br>    }<br>}</pre><h3>Step 2 — background</h3><p>When app goes background:</p><pre>stopPolling()</pre><p>You should also record:</p><pre>lastSuccessfulRefresh = Date()</pre><p>For example:</p><pre>lastSuccessfulRefresh = 8:00:00 PM</pre><p>Then app goes background at:</p><pre>8:02 PM</pre><h3>Step 3 — app remains backgrounded</h3><p>Don’t try to keep polling every 30 seconds using a normal timer.</p><p>Instead:</p><pre>App background<br>       ↓<br>Stop foreground polling<br>       ↓<br>Persist last refresh timestamp<br>       ↓<br>OS may suspend app</pre><h3>Step 4 — app returns</h3><p>Suppose user returns at:</p><pre>8:20 PM</pre><p>Your app calculates:</p><pre>let age = Date().timeIntervalSince(lastSuccessfulRefresh)</pre><p>Then:</p><pre>if age &gt; freshnessThreshold {<br>    await refresh()<br>}</pre><p>For example:</p><pre>Freshness threshold = 5 minutes</pre><pre>Last refresh = 8:02 PM<br>Current      = 8:20 PM</pre><pre>Age = 18 minutes</pre><p>So:</p><pre>Fetch immediately<br>↓<br>Update cache/UI<br>↓<br>Restart polling</pre><h3>This is the important design</h3><pre>APP ACTIVE<br>                        │<br>                        ▼<br>                  Start polling<br>                        │<br>                every 30 seconds<br>                        │<br>                        ▼<br>                   API refresh<br>                        │<br>              ┌─────────┴─────────┐<br>              │                   │<br>         App remains          App background<br>          active                   │<br>              │                    ▼<br>              │             Stop polling<br>              │                    │<br>              │             Save lastRefresh<br>              │                    │<br>              │               App suspended<br>              │                    │<br>              └───────┐      User returns<br>                      │           │<br>                      │           ▼<br>                      │      Check freshness<br>                      │           │<br>                      │      stale? ── yes<br>                      │           │<br>                      │           ▼<br>                      │       API refresh<br>                      │           │<br>                      │           ▼<br>                      └──── Restart polling</pre><p>This is much better than trying to preserve a timer across lifecycle states.</p><h3>What if I REALLY need background refresh?</h3><p>Then the requirement changes.</p><p>You might use:</p><h3>BGAppRefreshTask</h3><p>for short content refreshes, or:</p><h3>BGProcessingTask</h3><p>for longer processing.</p><p>Apple describes BGAppRefreshTask as short background refresh work and BGProcessingTask as longer processing that can take minutes. (<a href="https://developer.apple.com/documentation/backgroundtasks/bgapprefreshtaskrequest?changes=_1_5&amp;language=objc&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><p>But there’s a crucial point:</p><blockquote><em>BGAppRefreshTask is </em><strong><em>not</em></strong><em> an exact timer.</em></blockquote><p>For example, don’t tell the interviewer:</p><blockquote><em>“I’ll use BGAppRefreshTask every 15 minutes.”</em></blockquote><p>Instead say:</p><blockquote><em>“I’ll request background refresh at or after a desired earliest time, but the OS decides when to actually launch the task.”</em></blockquote><p>BGTaskRequest exposes earliestBeginDate, which is explicitly an earliest execution time rather than a guaranteed execution time. (<a href="https://developer.apple.com/documentation/backgroundtasks/bgtaskrequest?changes=_8&amp;language=objc&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><h3>So what would I say ?</h3><p>I’d say:</p><blockquote><em>“For foreground polling, I use a cancellable async task or timer and start/stop it based on scene lifecycle. When the app backgrounds, I stop polling and persist the last successful refresh time. On foreground, I calculate staleness and immediately refresh if necessary, then restart the polling loop. If background refresh is a product requirement, I use BGAppRefreshTask rather than assuming a timer can run while suspended. Background execution is system-scheduled, not a guaranteed periodic timer.”</em></blockquote><p>That’s a very senior-level answer.</p><h3>Scenario 2</h3><h3>Core Data has dirty objects but user terminates app</h3><p>Suppose:</p><pre>let user = User(context: context)<br>user.name = &quot;Sachin&quot;</pre><p>At this point:</p><pre>Memory<br>   ↓<br>Managed Object Context<br>   ↓<br>user.name = &quot;Sachin&quot;</pre><p>But you haven’t called:</p><pre>try context.save()</pre><p>Then the change is <strong>unsaved context state</strong>.</p><p>Core Data’s hasChanges tells you whether a context has uncommitted changes, and save() commits those changes to its parent store. (<a href="https://developer.apple.com/documentation/coredata/nsmanagedobject/managedobjectcontext?utm_source=chatgpt.com">Apple Developer</a>)</p><h3>What happens if app gets terminated?</h3><p>If you have:</p><pre>Managed Object<br>      ↓<br>Context<br>      ↓<br>NOT SAVED</pre><p>and the process disappears:</p><pre>💥 PROCESS TERMINATED</pre><pre>        In-memory context<br>              ↓<br>            LOST</pre><p>That dirty object is not magically recovered.</p><p>The persistent store contains only what was successfully committed.</p><h3>Example</h3><p>Suppose DB contains:</p><pre>Name = Rahul</pre><p>User changes:</p><pre>Name = Sachin</pre><p>but doesn’t save.</p><p>Then:</p><pre>Persistent Store = Rahul<br>Memory Context   = Sachin</pre><p>App gets killed.</p><p>Next launch:</p><pre>Persistent Store → Rahul</pre><p>not:</p><pre>Sachin</pre><h3>Therefore: save strategy matters</h3><p>I would never rely only on:</p><pre>applicationWillTerminate()</pre><p>for persistence.</p><p>Instead, I use <strong>durability boundaries</strong>.</p><p>For example:</p><h3>User edits an important object</h3><pre>context.perform {<br>    object.name = newName</pre><pre>    do {<br>        try context.save()<br>    } catch {<br>        // Handle persistence failure<br>    }<br>}</pre><p>Or batch multiple changes into a logical transaction:</p><pre>User edits profile<br>      ↓<br>Modify multiple objects<br>      ↓<br>Validate<br>      ↓<br>Save</pre><h3>Also save when app moves to background</h3><p>This is an additional safety boundary.</p><p>SwiftUI:</p><pre>.onChange(of: scenePhase) { _, phase in<br>    if phase == .background {<br>        persistenceController.saveIfNeeded()<br>    }<br>}</pre><p>But this should be viewed as:</p><blockquote><strong><em>an extra opportunity to persist</em></strong><em>, not your primary guarantee.</em></blockquote><p>Because iOS only gives a limited amount of background time, and termination can happen for several reasons. (<a href="https://developer.apple.com/documentation/uikit/extending-your-app-s-background-execution-time?changes=_8&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><h3>Better Core Data architecture</h3><p>For a large application:</p><pre>UI<br> │<br> ▼<br>ViewModel<br> │<br> ▼<br>Repository<br> │<br> ├── Main Context<br> │<br> └── Background Context<br>        │<br>        ▼<br>   Persistent Store</pre><p>For writes:</p><pre>User action<br>    ↓<br>Background context<br>    ↓<br>Perform changes<br>    ↓<br>save()<br>    ↓<br>Persistent store</pre><p>You should also correctly propagate saves through a parent/child context hierarchy if you use one. Apple’s documentation specifically points out that saving a child context doesn’t necessarily mean the external persistent store has been committed; the save must propagate through the context chain. (<a href="https://developer.apple.com/documentation/coredata/nsmanagedobjectcontext/save%28%29?changes=_2&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><h3>Production-grade strategy</h3><p>I would classify data.</p><h3>Critical user data</h3><p>Persist immediately or at well-defined transaction boundaries.</p><p>Examples:</p><pre>Booking<br>Payment state<br>Order<br>User profile<br>Draft</pre><h3>Noncritical/cache data</h3><p>It may be okay to persist asynchronously or rebuild from server.</p><p>Examples:</p><pre>API cache<br>Search results<br>Temporary metadata</pre><p>This is especially important in a payments architecture.</p><p>I would <strong>never</strong> keep something like:</p><pre>payment state<br>authorization result<br>booking confirmation</pre><p>only in an unsaved Core Data context.</p><h3>What about crashes?</h3><p>A crash is even more important than normal lifecycle handling.</p><p>For:</p><pre>context modified<br>context not saved<br>CRASH</pre><p>the changes are gone.</p><p>Therefore:</p><blockquote><strong><em>Persistence should happen when the data becomes semantically important, not only when the OS tells me the app is going away.</em></strong></blockquote><p>That’s a strong architectural statement.</p><h3>Scenario 3</h3><h3>Download files in foreground AND background</h3><p>This is where URLSession becomes very important.</p><p>Suppose you need:</p><pre>PDF = 200 MB<br>Video = 2 GB<br>Hotel voucher = 10 MB<br>Offline map = 500 MB</pre><p>You cannot design this as:</p><pre>URLSession.shared.dataTask(...)</pre><p>and expect the transfer to reliably continue after suspension.</p><p>For long-running background transfers, Apple’s recommended mechanism is a <strong>background </strong><strong>URLSession configuration</strong>. Background sessions allow uploads/downloads to continue while your app is suspended, and the system can relaunch your app to deliver completion events if needed. (<a href="https://developer.apple.com/documentation/foundation/downloading-files-in-the-background?changes=_2&amp;language=objc&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><h3>Architecture</h3><p>I’d create:</p><pre>DownloadManager<br>      │<br>      ▼<br>Background URLSession<br>      │<br>      ├── Download Task 1<br>      ├── Download Task 2<br>      ├── Download Task 3<br>      │<br>      ▼<br>File System<br>      │<br>      ▼<br>Persistence / Database<br>      │<br>      ▼<br>UI</pre><h3>Create a background session</h3><pre>final class DownloadManager: NSObject {<br>    static let shared = DownloadManager()</pre><pre>    private lazy var session: URLSession = {<br>        let configuration =<br>            URLSessionConfiguration.background(<br>                withIdentifier: &quot;com.company.app.downloads&quot;<br>            )</pre><pre>        configuration.isDiscretionary = false</pre><pre>        return URLSession(<br>            configuration: configuration,<br>            delegate: self,<br>            delegateQueue: nil<br>        )<br>    }()</pre><pre>    private override init() {<br>        super.init()<br>    }<br>}</pre><p>Then:</p><pre>func download(from url: URL) {<br>    let task = session.downloadTask(with: url)<br>    task.resume()<br>}</pre><h3>What happens if user backgrounds the app?</h3><pre>App active<br>   ↓<br>downloadTask.resume()<br>   ↓<br>User presses Home<br>   ↓<br>App enters background<br>   ↓<br>App may be suspended<br>   ↓<br>URLSession background transfer continues</pre><p>The important detail is that background URLSession work is handled by the system separately from ordinary application execution. Apple explicitly notes that the app may be suspended while the background download continues in another process. (<a href="https://developer.apple.com/documentation/foundation/downloading-files-in-the-background?changes=_2&amp;language=objc&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><h3>What if the app process is terminated by the system?</h3><p>This is where background URLSession is especially useful.</p><p>Apple says that if the system terminates your suspended app, it can relaunch the app in the background for the background transfer events. On launch, you recreate the background session using the <strong>same identifier</strong> so the OS can reassociate the transfer with your session/delegate. (<a href="https://developer.apple.com/documentation/foundation/downloading-files-in-the-background?changes=_2&amp;language=objc&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><p>So:</p><pre>App<br> ↓<br>start download<br> ↓<br>background<br> ↓<br>suspended<br> ↓<br>system terminates app<br> ↓<br>download continues<br> ↓<br>download completes<br> ↓<br>iOS relaunches app in background<br> ↓<br>recreate session with same identifier<br> ↓<br>delegate receives events<br> ↓<br>move file to permanent location</pre><p>That’s an excellent interview scenario to explain.</p><h3>Delegate implementation</h3><p>For example:</p><pre>extension DownloadManager:<br>    URLSessionDownloadDelegate {</pre><pre>    func urlSession(<br>        _ session: URLSession,<br>        downloadTask: URLSessionDownloadTask,<br>        didFinishDownloadingTo location: URL<br>    ) {</pre><pre>        let fileManager = FileManager.default</pre><pre>        let documentsURL =<br>            fileManager.urls(<br>                for: .documentDirectory,<br>                in: .userDomainMask<br>            )[0]</pre><pre>        let destination =<br>            documentsURL.appendingPathComponent(<br>                &quot;downloaded-file.pdf&quot;<br>            )</pre><pre>        do {<br>            if fileManager.fileExists(atPath: destination.path) {<br>                try fileManager.removeItem(at: destination)<br>            }</pre><pre>            try fileManager.moveItem(<br>                at: location,<br>                to: destination<br>            )<br>        } catch {<br>            print(&quot;File move failed:&quot;, error)<br>        }<br>    }<br>}</pre><p>Why move it?</p><p>Because the URL provided by didFinishDownloadingTo is a temporary location, and Apple says you need to move the file to a permanent location if you want to retain it. (<a href="https://developer.apple.com/documentation/foundation/downloading-files-in-the-background?changes=_2&amp;language=objc&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><h3>Very important: background session events</h3><p>In a production app, I also handle the background-session lifecycle at the app entry point.</p><p>Conceptually:</p><pre>iOS<br> ↓<br>background download finishes<br> ↓<br>iOS launches/resumes application<br> ↓<br>AppDelegate receives background URLSession event<br> ↓<br>recreate session<br> ↓<br>delegate processes completion<br> ↓<br>persist download state<br> ↓<br>call completion handler</pre><p>For SwiftUI, you can still integrate an app delegate using:</p><pre>@UIApplicationDelegateAdaptor(AppDelegate.self)<br>var appDelegate</pre><p>This is one of those cases where being “SwiftUI” doesn’t mean the UIKit lifecycle infrastructure disappears.</p><h3>What if the user force-quits the app?</h3><p>This is a separate case and an important interview trap.</p><p>Force-quitting is different from the system merely suspending/terminating your process.</p><p>Apple documents that a user force-quit can cause the system to cancel background URLSession work, with NSURLErrorCancelledReasonUserForceQuitApplication identifying that reason. (<a href="https://developer.apple.com/documentation/foundation/nsurlerrorcancelledreasonuserforcequitapplication?changes=_1_5&amp;utm_source=chatgpt.com">Apple Developer</a>)</p><p>So I would tell the interviewer:</p><blockquote><em>“System termination and user force-quit are different. Background URLSession is designed to survive suspension and system termination, but I don’t assume it can continue after the user explicitly force-quits the app.”</em></blockquote><p>That’s an important distinction.</p><h3>What if download is already happening in foreground?</h3><p>You can use the same URLSession infrastructure.</p><p>For example:</p><pre>DownloadManager<br>                          │<br>              ┌───────────┴───────────┐<br>              │                       │<br>        Foreground UX           Background transfer<br>              │                       │<br>              └───────────┬───────────┘<br>                          │<br>                   URLSession task</pre><p>UI can observe:</p><pre>queued<br>↓<br>downloading<br>↓<br>paused<br>↓<br>completed<br>↓<br>failed</pre><p>The transfer itself should be independent of the view.</p><p>This is a key architectural principle:</p><blockquote><strong><em>A download should belong to a service/manager, not to a View or ViewModel.</em></strong></blockquote><p>Otherwise you get:</p><pre>View disappears<br>   ↓<br>ViewModel deallocated<br>   ↓<br>Download logic disappears</pre><p>which is exactly what you don’t want.</p><h3>How I would persist download state</h3><p>For serious apps:</p><pre>DownloadTask<br>-------------------------<br>id<br>remoteURL<br>localURL<br>status<br>progress<br>createdAt<br>completedAt<br>errorCode<br>retryCount</pre><p>You can keep that metadata in:</p><ul><li>Core Data</li><li>SQLite</li><li>another persistent store</li></ul><p>Then on app launch:</p><pre>Read pending downloads<br>        ↓<br>Rebuild DownloadManager state<br>        ↓<br>Reconnect to URLSession tasks<br>        ↓<br>Update UI</pre><p>This means the UI isn’t dependent on whether the process survived.</p><h3>The bigger architecture</h3><p>This is the architecture I would use for a large consumer iOS app:</p><pre>┌───────────────────┐<br>                       │      SwiftUI      │<br>                       │       Views       │<br>                       └─────────┬─────────┘<br>                                 │<br>                                 ▼<br>                       ┌───────────────────┐<br>                       │    ViewModel      │<br>                       └─────────┬─────────┘<br>                                 │<br>                 ┌───────────────┼────────────────┐<br>                 │               │                │<br>                 ▼               ▼                ▼<br>          PollingService     Repository     DownloadManager<br>                 │               │                │<br>                 │               ▼                ▼<br>                 │          Core Data        URLSession<br>                 │               │                │<br>                 ▼               ▼                ▼<br>             API Client      Persistent      File System<br>                                Store</pre><p>And lifecycle sits above these services:</p><pre>iOS Lifecycle<br>                       │<br>          ┌────────────┼────────────┐<br>          ▼            ▼            ▼<br>       Active       Background   Terminated<br>          │            │            │<br>          ▼            ▼            ▼<br>      Start work    Stop normal    Reconstruct<br>      Refresh       polling        state</pre><h3>The three scenarios summarized</h3><p>RequirementForegroundBackgroundSuspended / TerminatedNormal API polling✅ Timer / async task❌ Don’t rely on timer❌Refresh eventually in background✅BGAppRefreshTaskOS may relaunch taskCritical local persistence✅ Save✅ Save during lifecycle opportunityAlready persisted data survivesUnsaved Core Data changesIn memoryRisky❌ LostLarge file downloadURLSessionBackground URLSession✅ System can continue/relaunch for transferUser force-quit——Background work may be cancelled</p><h3>One concept that ties all three together</h3><p>Imagine this state:</p><pre>App:<br>    foreground<br>    ↓<br>API call<br>    ↓<br>Core Data changes<br>    ↓<br>Download started<br>    ↓<br>User goes Home</pre><p>A weak implementation says:</p><pre>&quot;My objects, timers, tasks and downloads are all alive<br>because my app is alive.&quot;</pre><p>A strong implementation says:</p><pre>iOS may suspend or kill me at any moment.</pre><pre>Therefore:</pre><pre>API freshness<br>    → timestamp + lifecycle-aware refresh</pre><pre>Persistence<br>    → save to persistent store before data matters</pre><pre>Long-running download<br>    → background URLSession</pre><pre>Background refresh<br>    → BGTaskScheduler where appropriate</pre><pre>UI<br>    → observes durable state</pre><p>That’s the <strong>system-design mindset</strong> interviewers look for at a senior level.</p><h3>You can almost memorize this:</h3><blockquote><strong><em>“iOS has foreground active, foreground inactive, background, suspended and terminated execution conditions, with modern apps additionally having scene-level states such as unattached. SwiftUI exposes those through ScenePhase while UIKit uses UISceneDelegate. The key point is that background does not mean continuously executing — the system can suspend the process.</em></strong></blockquote><blockquote><strong><em>For periodic APIs, I don’t rely on Timer in the background. I stop foreground polling when entering background, persist the last refresh time, and on foreground calculate data staleness and refresh immediately if required. For true background refresh, I use BGAppRefreshTask or another appropriate background mechanism, understanding that execution isn’t guaranteed at an exact interval.</em></strong></blockquote><blockquote><strong><em>For Core Data, I don’t depend on applicationWillTerminate. Unsaved context changes are in memory and can be lost if the process terminates. I save at meaningful transaction boundaries and use the background lifecycle as an additional save opportunity.</em></strong></blockquote><blockquote><strong><em>For file downloads that need to survive backgrounding, I use a background URLSession. The system can continue the transfer while my app is suspended and can relaunch the app for completion events after system termination. I recreate the session with the same identifier and move the completed temporary file to permanent storage. User force-quit is a special case where I don’t assume the transfer will continue.”</em></strong></blockquote><p>That answer demonstrates <strong>lifecycle knowledge + reliability + persistence + background execution + architecture</strong>, rather than just knowing individual APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aeba3d7c298" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Copyable, Borrowing, and Consuming in Swift]]></title>
            <link>https://sabatsachin.medium.com/understanding-copyable-borrowing-and-consuming-in-swift-2fba56a07313?source=rss-fad79356b8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fba56a07313</guid>
            <dc:creator><![CDATA[Sachin Sabat]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 07:18:11 GMT</pubDate>
            <atom:updated>2025-03-05T07:23:01.425Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous article, I discussed <strong>Move-Only Types</strong> and <strong>Non-Copyable Protocols</strong> in Swift. This follow-up post dives into three closely related concepts that further enhance safe and efficient resource management in Swift: <strong>Copyable</strong>, <strong>Borrowing</strong>, and <strong>Consuming</strong>.</p><ul><li><strong>Copyable:</strong> How and when values can be duplicated.</li><li><strong>Borrowing:</strong> Temporarily accessing a resource without taking ownership.</li><li><strong>Consuming:</strong> Transferring full ownership, invalidating the original reference.</li></ul><p>Understanding these ideas will help you design robust Swift code, particularly when dealing with resources that must remain unique.</p><p>Let’s break these down with code examples and real-world scenarios.</p><h3>1. Copyable Types</h3><h3>What Does “Copyable” Mean?</h3><p>In Swift, many types (such as structs and enums) are <em>copyable by default</em>. This means that when you assign or pass them around, Swift creates a duplicate. While this behavior is ideal for immutable data (like app configurations), it can lead to issues for resources that should remain unique.<br>However, for certain resources (like file handles or locks) we want to restrict copying. With <strong>move-only types</strong> and non-copyable protocols, we explicitly mark types as not copyable. For now, let’s see an example of a simple copyable type.</p><h3>Swift Code Example: A Copyable Configuration</h3><pre>struct AppConfiguration {<br>    var theme: String<br>    var apiEndpoint: String<br>}<br><br>var config1 = AppConfiguration(theme: &quot;Light&quot;, apiEndpoint: &quot;https://api.example.com&quot;)<br>var config2 = config1  // A copy is made<br>config2.theme = &quot;Dark&quot;<br><br>print(&quot;Config1 Theme:&quot;, config1.theme) // &quot;Light&quot;<br>print(&quot;Config2 Theme:&quot;, config2.theme) // &quot;Dark&quot;</pre><h3>Real-World Analogy</h3><p>Think of a configuration file for an app — this is something that can be copied and modified independently (like a photocopy of a document). Each copy can be tweaked without affecting the original.</p><p><strong>More Realistic example-</strong> Imagine you have an original blueprint for building a house. Because blueprints are designed to be copyable, you can make several photocopies and distribute them to different teams (plumbing, electrical, construction) to work independently. Each team gets a copy that they can mark up or refer to without affecting the original. In this case, copying is beneficial — it allows multiple people to work in parallel without conflict.</p><h3>2. Borrowing</h3><h3>What Is Borrowing?</h3><p><strong>Borrowing</strong> is like temporarily lending someone your resource without giving up ownership, it allows temporary access to a resource without transferring its ownership. When you borrow, the original resource stays valid and owned by you, but the borrower gets temporary read (or sometimes mutable) access.</p><h3>Swift Code Example: Borrowing a Move-Only Resource</h3><p>Imagine a file handle modeled as a move-only type:</p><pre>@moveOnly<br>struct FileHandle {<br>    let descriptor: Int<br><br>    func read() {<br>        print(&quot;Reading from file with descriptor \(descriptor)&quot;)<br>    }<br>}<br><br>func borrowFile(handle: FileHandle) {<br>    // Borrowing the handle to read without taking ownership.<br>    handle.read()<br>}<br><br>var file = FileHandle(descriptor: 101)<br>borrowFile(handle: file)<br>// The original &#39;file&#39; remains valid after borrowing.<br>file.read()</pre><h3>Real-World Analogy</h3><p>Borrowing is like lending a book to a friend for a quick read. The friend can read it (access the resource), but the book still belongs to you and remains in your collection.</p><p>More Realistic example- Imagine you own a rare, first-edition book that is extremely valuable. A friend asks to borrow it for a short period to study its content. You hand over the book, but you set clear rules: they must return it in the same condition and cannot make any permanent changes. During the borrowing period, you trust your friend to handle the book carefully while you remain the owner. Once returned, the book is still yours and can be lent out again. This careful, temporary lending is akin to borrowing in Swift — temporary access without relinquishing ownership.</p><h3>3. Consuming</h3><h3>What Does Consuming Mean?</h3><p><strong>Consuming</strong> is when you transfer ownership of a resource. After consumption, the original owner loses access. This is critical for resources that must be unique — once handed off, they shouldn’t be used again by the original owner. To simplify, After consumption, the original owner loses access, ensuring the resource remains unique and is not used simultaneously in conflicting ways.</p><h3>Swift Code Example: Consuming a Resource</h3><p>Consider a unique session in an AR application:</p><pre>@moveOnly<br>struct UniqueSession {<br>    let id: String<br><br>    func start() {<br>        print(&quot;Starting session with id \(id)&quot;)<br>    }<br>    <br>    func end() {<br>        print(&quot;Ending session with id \(id)&quot;)<br>    }<br>}<br><br>// A consuming function—ownership of `session` is transferred.<br>func consumeSession(_ session: consuming UniqueSession) {<br>    session.start()<br>    session.end()<br>}<br><br>var session = UniqueSession(id: &quot;AR-2025&quot;)<br>// Transfer ownership—`session` is consumed by the function.<br>consumeSession(session)<br>// session.start() // Error: &#39;session&#39; is no longer valid after being consumed.</pre><h3>Real-World Analogy</h3><p>Consuming a resource is like selling your car. Once you hand over the keys, you no longer have access — the new owner assumes full control.</p><p>More Realistic example- Imagine you own a classic car that is one-of-a-kind. One day, you decide to sell it to a collector. Once you transfer the keys and ownership documents to the buyer, the car is no longer yours — you cannot drive it, modify it, or lend it out. The entire asset, with all its unique value and history, has been handed off to someone else, ensuring that it exists in only one place. This complete handover mirrors consuming in Swift, where a resource’s ownership is fully transferred, leaving the original reference invalid.</p><h3>SwiftUI Integration Example</h3><p>While SwiftUI is built on value types (which are copyable by default), you can still benefit from these ownership concepts in your app’s architecture. Imagine you have a view that interacts with a unique data source that must not be duplicated.</p><h3>SwiftUI Example: A Unique Data Manager</h3><pre>import SwiftUI<br><br>// Hypothetical move-only data manager<br>@moveOnly<br>class UniqueDataManager: ObservableObject {<br>    @Published var data: String = &quot;Initial Data&quot;<br>    <br>    func updateData(newData: String) {<br>        data = newData<br>        print(&quot;Data updated to:&quot;, newData)<br>    }<br>}<br><br>struct ContentView: View {<br>    @StateObject private var manager = UniqueDataManager()<br>    <br>    var body: some View {<br>        VStack(spacing: 20) {<br>            Text(manager.data)<br>                .padding()<br>            <br>            Button(&quot;Update Data&quot;) {<br>                // Borrowing the manager reference to update data<br>                manager.updateData(newData: &quot;Updated Data&quot;)<br>            }<br>        }<br>        .padding()<br>    }<br>}</pre><h3>Explanation</h3><ul><li><strong>Ownership:</strong> The UniqueDataManager is managed as a single, unique instance using @StateObject.</li><li><strong>Borrowing:</strong> When updating or reading data, the view temporarily accesses the manager without transferring ownership.</li><li><strong>Consuming (Hypothetical):</strong> If you needed to permanently hand off the manager (for instance, to shut down a service), you would consume it.</li></ul><h3><strong>In summary:</strong></h3><ul><li><strong>Copyable types</strong> let you duplicate values freely, useful for immutable configurations.</li><li><strong>Borrowing</strong> allows safe, temporary access to a resource without transferring ownership.</li><li><strong>Consuming</strong> transfers full ownership, ensuring that a unique resource isn’t used simultaneously in two places.</li></ul><p>By combining <strong>Copyable</strong>, <strong>Borrowing</strong>, and <strong>Consuming</strong> concepts with move-only types and non-copyable protocols, Swift enables you to write safer, more efficient, and clearer code — especially when handling unique or critical resources.</p><p>Whether you’re managing file handles, unique sessions, or specialized data managers, understanding and applying these principles can make your Swift code robust and less prone to resource conflicts.</p><p>Feel free to share your thoughts or questions in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fba56a07313" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Move-Only Types & Non-Copyable Protocols in Swift basic concepts]]></title>
            <link>https://sabatsachin.medium.com/move-only-types-non-copyable-protocols-in-swift-890f6f37a18c?source=rss-fad79356b8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/890f6f37a18c</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Sachin Sabat]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 12:36:41 GMT</pubDate>
            <atom:updated>2024-12-02T09:48:39.803Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift evolves to handle advanced ownership and resource management scenarios which introduced <strong>Move-Only Types and the concept of Non-Copyable Protocols</strong>. These features aim to enhance the language’s safety, efficiency, and expressiveness by preventing the duplication of certain types and it enables exclusive ownership semantics.</p><h3>The Challenge-</h3><h4>The Problem with Copying</h4><p>In Swift, value types are copyable by default, meaning assigning or passing them creates a copy. This behavior is great for simple use cases but becomes problematic in scenarios like:</p><ul><li>File Handles: Duplicating a file handle can lead to two processes writing to the same file simultaneously, causing corruption.</li><li>Large Resources: Copying large data structures unnecessarily consumes memory and processing power.</li></ul><h4>The Need for Change</h4><ol><li>A way to prevent copying for certain types.</li><li>A way to ensure exclusive ownership of resources.</li></ol><p><strong>Copyable Example:</strong></p><pre>struct ARSession {<br>    var configuration: String<br>}<br><br>var session1 = ARSession(configuration: &quot;HighResolution&quot;)<br>var session2 = session1  // Copy allowed<br>session2.configuration = &quot;LowResolution&quot;<br>print(session1.configuration) // Still &quot;HighResolution&quot;</pre><p><strong>Drawback:</strong> This works for lightweight configurations but may introduce issues if you were to manage hardware-specific resources, as duplicating such objects could cause conflicts.</p><p><strong>Non-Copyable Example:</strong></p><pre>final class ARSession {<br>    private init() {}<br>    static func create() -&gt; ARSession {<br>        return ARSession()<br>    }<br>    <br>    func configureSession(_ configuration: String) {<br>        print(&quot;Configuring AR session with \(configuration)&quot;)<br>    }<br>}<br><br>let session = ARSession.create()<br>session.configureSession(&quot;HighResolution&quot;)<br>// session2 = session // Cannot create another reference directly.</pre><p><strong>Advantage:</strong> Only one AR session can exist at a time, ensuring proper resource usage and avoiding hardware conflicts.</p><h3>What is Move-Only Types?</h3><h4>Introduction:</h4><p>Move-only types ensure that a value can only be moved (ownership transferred) and not copied. This prevents duplication and ensures that only one “owner” exists at any time.</p><h4>How Move-Only Types Work?</h4><ol><li>When a move-only value is assigned to another variable or passed as an argument, ownership transfers to the new location.</li><li>The original value becomes invalid and cannot be used anymore.</li></ol><h4><strong>To make it more simpler to understand-</strong></h4><p><strong>Think of move-only types like a concert ticket:</strong></p><ul><li>You can give the ticket to a friend (ownership transfer), but you can’t both keep and use it.</li><li>Once you’ve given away the ticket, you can’t enter the concert anymore.</li><li>This ensures that only one person uses the ticket, preventing issues at the concert gate.</li></ul><h4>Key Features of Move-Only Types</h4><ul><li>Safety: Prevents accidental duplication of resources.</li><li>Exclusive Ownership: Only one reference to the value exists at a time.</li><li>Efficiency: Reduces memory and processing overhead by avoiding unnecessary copies.</li><li>Compile-Time Enforcement: Swift’s type system will statically enforce move-only semantics, catching errors at compile time.</li></ul><h4>Benefits of Move-Only Types</h4><ol><li>Prevents Bugs: Ensures that unique resources aren’t accidentally duplicated, which could cause runtime issues.</li><li>Efficient: Avoids unnecessary copying of large or complex resources.</li><li>Clear Ownership: Makes it obvious who is responsible for managing a resource.</li></ol><h4><strong>Example</strong>-</h4><pre>@moveOnly<br>struct UniqueResource {<br>    var data: String<br><br>    init(data: String) {<br>        self.data = data<br>    }<br><br>    func use() {<br>        print(&quot;Using resource with data: \(data)&quot;)<br>    }<br>}</pre><h4>Example of Ownership Transfer:</h4><pre>func processResource(_ resource: UniqueResource) {<br>    resource.use()<br>}<br><br>var resource = UniqueResource(data: &quot;Important Data&quot;)<br>// Ownership of `resource` is moved to the function.<br>// `resource` becomes invalid after the move.<br>processResource(resource)<br>// resource.use() // Error: `resource` is no longer accessible.</pre><h4>Invalid Copying:</h4><pre>var resource1 = UniqueResource(data: &quot;Resource 1&quot;)<br>var resource2 = resource1 // Error: Cannot copy a move-only type.</pre><h3>Non-Copyable Protocols</h3><h4>What Are Non-Copyable Protocols?</h4><p>A non-copyable protocol ensures that any type conforming to it cannot be duplicated. This is useful for defining behavior that inherently requires unique ownership.</p><p>Examples include:</p><ul><li>File handles</li><li>Hardware locks</li><li>Database connections</li><li>Unique tokens or session objects</li></ul><h4>Lets look at the Implementation of Non-Copyable Protocols…</h4><h4>Approach 1: Move-Only Types</h4><pre>@moveOnly<br>protocol NonCopyable {<br>    func useResource()<br>}<br><br>@moveOnly<br>struct UniqueResource: NonCopyable {<br>    let resourceID: Int<br><br>    init(resourceID: Int) {<br>        self.resourceID = resourceID<br>    }<br><br>    func useResource() {<br>        print(&quot;Using unique resource \(resourceID)&quot;)<br>    }<br>}<br><br>// Usage<br>func process(resource: UniqueResource) {<br>    resource.useResource()<br>}<br><br>let resource = UniqueResource(resourceID: 1)<br>process(resource)<br>// resource.useResource() // Error: resource is no longer valid after the move.</pre><p>Here:</p><ol><li>The UniqueResource struct conforms to the NonCopyable protocol.</li><li>Ownership is transferred when the resource is passed to the process function.</li><li>The original resource becomes invalid.</li></ol><h4>Approach 2: Restricted Initializers and References</h4><p>You can restrict copying by:</p><ol><li>Using final class types to enforce reference semantics.</li><li>Preventing explicit copying with private copy constructors.</li></ol><p>Example:</p><pre>protocol NonCopyable {<br>    func useResource()<br>}<br><br>final class UniqueResource: NonCopyable {<br>    private init() {}<br>    <br>    static func create() -&gt; UniqueResource {<br>        return UniqueResource()<br>    }<br><br>    func useResource() {<br>        print(&quot;Using unique resource&quot;)<br>    }<br><br>    private func copy() -&gt; UniqueResource {<br>        fatalError(&quot;Copying is not allowed for UniqueResource&quot;)<br>    }<br>}<br><br>// Usage<br>let resource = UniqueResource.create()<br>resource.useResource()<br>// let copiedResource = resource.copy() // Error: Copying is disabled.</pre><p>Key points:</p><ul><li>The UniqueResource class prevents copying via a private copy constructor.</li><li>It can only be instantiated via a static factory method.</li></ul><h4>Approach 3: Using Enums for Explicit Ownership</h4><p>You can also use enums to enforce single ownership of resources:</p><pre>protocol NonCopyable {<br>    func useResource()<br>}<br><br>enum UniqueResource: NonCopyable {<br>    case available(String)<br>    case consumed<br><br>    mutating func useResource() {<br>        guard case let .available(data) = self else {<br>            fatalError(&quot;Resource has already been used&quot;)<br>        }<br>        print(&quot;Using resource with data: \(data)&quot;)<br>        self = .consumed<br>    }<br>}<br><br>// Usage<br>var resource = UniqueResource.available(&quot;ARSessionData&quot;)<br>resource.useResource()<br>// resource.useResource() // Error: Resource has already been consumed.</pre><h3>When to Use Non-Copyable Protocols</h3><ul><li>Unique Resource Management: Managing hardware locks, file handles, or other system-level resources that cannot be duplicated.</li><li>Memory Efficiency: Reducing memory overhead by enforcing single ownership.</li><li>Safety: Preventing accidental duplication or unintended sharing of critical resources.</li></ul><h4>Difference from Move-Only Types</h4><ul><li>Move-Only Types: Focus on preventing copying for individual types.</li><li>Non-Copyable Protocols: Provide a blueprint for types that must not be copied.</li></ul><h3>Real-World Applications</h3><h4>File Handling</h4><p>A file handle is a resource that cannot be duplicated. Using a move-only type ensures that each file handle has a single owner.</p><pre>@moveOnly<br>struct FileHandle {<br>    let descriptor: Int<br><br>    init(descriptor: Int) {<br>        self.descriptor = descriptor<br>    }<br><br>    func close() {<br>        print(&quot;File \(descriptor) closed.&quot;)<br>    }<br>}</pre><h4>AR Sessions in Application using ARKit-</h4><p>In an AR app, non-copyable protocols can be useful for managing AR sessions. Only one AR session should be active at a time to avoid hardware conflicts.</p><pre>@moveOnly<br>protocol ARSessionManager {<br>    func configureSession()<br>    func endSession()<br>}<br><br>@moveOnly<br>struct ARSession: ARSessionManager {<br>    func configureSession() {<br>        print(&quot;Configuring AR session&quot;)<br>    }<br>    <br>    func endSession() {<br>        print(&quot;Ending AR session&quot;)<br>    }<br>}<br><br>// Usage<br>var session = ARSession()<br>session.configureSession()<br>// Passing ownership<br>func handleSession(_ session: ARSession) {<br>    session.endSession()<br>}<br>handleSession(session)<br>// session.configureSession() // Error: session is no longer valid.</pre><h4>Power of Non-Copyable Protocols in Space and Time</h4><ul><li>Space Efficiency: Avoids memory waste by ensuring no duplicates are created.</li><li>Time Efficiency: Reduces overhead from unnecessary copying and synchronization.</li><li>Safety: Ensures that only one unique resource instance is active, preventing undefined behavior.</li></ul><h3>What is the The Future?</h3><h4>Move-Only Types in Swift</h4><p>Swift’s type system is evolving to natively support move-only types, making them a first-class feature. This will simplify resource management and enhance safety in Swift programs.</p><h4>Non-Copyable Protocols</h4><p>While not officially part of the language yet, non-copyable protocols are a natural extension of move-only types. They provide additional flexibility for designing APIs and systems that require exclusive ownership semantics.</p><h3><strong>The Takeaway</strong></h3><p>Move-only types and non-copyable protocols represent a significant step forward in Swift’s ability to handle unique ownership and resource safety. They enable developers to write safer, more efficient code, especially for systems-level programming or applications that manage critical resources.</p><h4><strong>We will cover ~copyable, borrowing and consuming in coming blogs.</strong></h4><p>Connect with me to improve or share many insights on Move-Only Types &amp; Non-Copyable Protocols.</p><p><a href="https://www.linkedin.com/in/sachinsabat/">Sachin Sabat - System Engineer - Tata Consultancy Services | LinkedIn</a></p><p>Thank You…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=890f6f37a18c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobile Application Testing]]></title>
            <link>https://sabatsachin.medium.com/mobile-application-testing-abad00e67eca?source=rss-fad79356b8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/abad00e67eca</guid>
            <dc:creator><![CDATA[Sachin Sabat]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 16:18:55 GMT</pubDate>
            <atom:updated>2024-04-10T16:18:55.994Z</atom:updated>
            <content:encoded><![CDATA[<p>Things required to test mobile application in detail and knowledge required to become a tester for mobile application.</p><h3>5 main business model-</h3><ol><li>Freemium — App is free, Pay for additional feature, App must be attractive ( eg. Dropbox, Slack)</li><li>Advertisement — Effective is app is used for longer time, No UX should be distorted, Too much ads avoid it.</li><li>Transaction based- Charge user per transaction, suitable for limited number of application (Eg- Udemy)</li><li>Fee based- Pay for download, must provide outstanding feature (eg- Netflix)</li><li>Enterprise- Developed for internal use withing the org, developed but revenue is not generated. (eg- banks &amp; e-comm provide enterprise, youtube studio)</li></ol><p>Ways to monetise our application:</p><ol><li>In-app purchase</li><li>In-app advertisement</li></ol><h3>Types of mobile device</h3><ol><li>Basic type- Used for telephone and SMS, few built-in apps and games, browsing not possible</li><li>Feature Phone- Limited for apps, browsing and limited hardware support like camera</li><li>Smartphones- Several sensor, app install is done</li><li>Tablet- larger than smartphone, longer battery life, may have 2 version of OS version for apple.</li><li>Companion device- Computer powered device, used with smartphone/ tablet, wearable are example of this device.</li></ol><h3>Types of mobile application</h3><ol><li>Native- Good performance, high cost, installed on device. eg- google maps, fb</li><li>Browser based- Accessed through mobile browser, low cost, easy to develop, browser compatibility testing is required.</li><li>Hybrid- Combination of native &amp; web, easy to develop, work offline</li></ol><h3>Mobile application architecture</h3><ol><li>Thin client- Dont have code customised to device, make min use of operating system features, web browser as front end &amp; java script</li><li>Thick client- Multiple layer of app code, use mobile OS, either native or hybird app</li><li>Server side architecture- <br>1. Single tier- all server on the same page, less scalable, less secure<br>2. Multi- tier- spread server-side component, allows separation of responsibilities, scalable, secure, flexible, 2tier has web and db server whereas 3tier has app server</li><li>Connection methods- Never connected(calculator), always connected (web app) and partially connected(udemy)</li><li>Data sync- Continous mode (live video), Store and forward(record a video and send)</li><li>Data transfer- sync transfer (video conference), async transfer (email)</li></ol><h3>Challenges faced during testing</h3><ol><li>Multiple platform &amp; device</li><li>Diff UI &amp; UX expectation</li><li>Multiple network type</li><li>Resource- starved device</li><li>Diverse user</li><li>High feedback availability</li><li>Market place publishing approval</li><li>Unavailability of new device</li></ol><h3>Risk faced during testing</h3><ol><li>Market fragmentation (test the most commonly used device)</li><li>Cost of supporting multiple platform(perform analysis to understand most used platform)</li><li>Intro of new tech platform and device(apply remote device), risk from expected usage pattern of app used while on the go (field testing).</li></ol><h3>Test Strategy</h3><ol><li>Challenge- Large number of device (single platform, multiple platform, maximum coverage approach)</li><li>Challenge- Non-availability of device, network, or real-life condition (remote device access, crowd testing, personal network, bug hunting)</li></ol><h3>Test for diff display</h3><ol><li>Screen size- Size in diagonal in inches</li><li>Viewport size- Actual visible area of website on screen</li><li>Aspect ratio- Proportional between height and width of rectangle</li><li>Resolution- number of hor and ver pixel on display screen (ppi or dpi)</li></ol><h3>Test for diff screen orientation</h3><ol><li>correct usability and functionality</li><li>app maintain its state</li><li>input data retain already captured data</li><li>output data displays the same data</li></ol><h3>Test for typical interrupt</h3><ol><li>Device — voice call, message</li><li>User — app switching</li></ol><h3>Test for power consumption and state</h3><ol><li>Battery power state and drainage related defects</li><li>power consumption while app on active and background</li><li>Log analyser needed</li></ol><h3>Test for access permission, device feature, device temp, device input sensor, various input methods, notification</h3><h3>Test for quick access link</h3><ol><li>Force touch</li><li>3D touch</li><li>Haptic touch</li><li>App shortcut</li></ol><h3>Stress Testing</h3><ol><li>High CPU usage</li><li>Out of memory</li><li>Low disk space</li><li>Battery space</li><li>failure</li><li>Poor bandwidth</li><li>Very high number of user interactions</li></ol><h3>Security Testing</h3><ol><li>Access to sensitive storage, unencrypted information transformed</li><li>Testing inputs for overflow</li><li>Encryption of locally and transferred data</li><li>deletion of temporary data</li><li>clear text in password field</li></ol><h3>Performance Testing</h3><ol><li>Check for chronometry</li></ol><h3>Usability Testing</h3><ol><li>Heuristic, test tour, personas</li></ol><h3>Db Testing</h3><ol><li>Sync of data storage</li><li>upload conflicts</li><li>data security</li><li>constraints on data</li><li>CRUD functionality</li><li>Data integration by third party apps (contact)</li><li>performance on storing data on device</li></ol><h3>Persona Testing</h3><ol><li>Basis on location, age eg. facebook</li></ol><h3>SFIDPOT</h3><ol><li>Structure</li><li>Function</li><li>Input</li><li>Data</li><li>Platform</li><li>Operation</li><li>Time</li></ol><h3>I Sliced up fun</h3><ol><li>Input</li><li>Store</li><li>Location</li><li>Interaction</li><li>Communication</li><li>Ergonomics</li><li>Data</li><li>Usability</li><li>Platform</li><li>Function</li><li>User scenario</li><li>Network</li></ol><h3>Session based test management (SBTM)</h3><ol><li>Session setup</li><li>Test design &amp; execution</li><li>Issue investigation &amp; reporting</li><li>session sheet</li></ol><h3>Test planning</h3><ol><li>Device combination</li><li>use of emulator and simulator</li><li>special challenges</li><li>test types specially required</li><li>App store approval</li><li>Field (Analysis &amp; design and Implementation &amp; execution)</li><li>Device compatibility</li><li>Simulator- models the runtime env</li><li>Emulator- models the hardware &amp; utilise the same runtime env as the physical hardware, it reduces the cost of real device for some testing</li></ol><h3>Automation approach</h3><ol><li>User-agent based-Uses browser</li><li>Device-based- Direct on device</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abad00e67eca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State/ Data Flow Management in SwiftUI for iOS v17.0-]]></title>
            <link>https://sabatsachin.medium.com/state-data-flowmanagement-in-swiftui-53f53b4b17fd?source=rss-fad79356b8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/53f53b4b17fd</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Sachin Sabat]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 17:40:15 GMT</pubDate>
            <atom:updated>2024-04-19T14:54:44.169Z</atom:updated>
            <content:encoded><![CDATA[<h3>State/ Data Flow Management in SwiftUI for iOS v17.0- @State @Bindable @Environment @ObservableObject @Published</h3><p>We will cover all the mechanism used for managing the data within views of the application in SwiftUI</p><h3><strong>What is SwiftUI?</strong></h3><p>It is a new <strong>declarative framework</strong> for building apps for MacOS, iOS, WatchOS, tvOS. Also, with the support for iPad. This declarative framework code will run on all above platform as mentioned. Also, we can easily create new interfaces with this framework.</p><h4><strong>Now, What is declarative framework?</strong></h4><p>It simplifies the process of building user interfaces by abstracting away the complexities of manual UI manipulation and providing a more intuitive and efficient way to describe UI elements and their behavior. To make it more simpler, It is a way to build user interfaces for your apps by simply describing what you want, and letting SwiftUI handle the rest. It’s like telling someone how you want your room decorated, and they magically make it happen without you having to lift a finger!</p><p>So, with this declarative syntax, we can create apps much faster than with UIKit, which might take a couple of days. Here, it will take only a couple of hours.</p><p>Lets go through the types of properties for managing data in the views in <strong>@available</strong>(iOS 17.0, *) -</p><h3><strong>@State property wrapper-</strong></h3><p>This is used for local private data for the view. This property wrapper is used to declare a property within a view that is mutable and triggers view updates when its value changes. It means when a @State variable changes, SwiftUI automatically updates the corresponding view to reflect the new state.</p><pre>struct ContentView: View {<br>    <br>    @State private var increaseTheCount: Int = 0<br><br>    var body: some View {<br>        let _ = Self._printChanges()<br>        <br>        VStack(alignment: .center) {<br>            Button(&quot;Add&quot;) {<br>                increaseTheCount += 1<br>            }<br>        }<br>        .padding()<br>    }<br>}</pre><p>In the code above, we are not calling increaseTheCount in any view so the body is not getting rendered as the property marked with @state property wrappers allows our view to rebuild and rendered. Above code increaseTheCount is marked with @state but we are not displaying/ using it anywhere in our view. So SwiftUI is smart enough to not re rendered the view even though we are changing the @state property.</p><pre>struct ContentView: View {<br>    <br>    @State private var increaseTheCount: Int = 0<br><br>    var body: some View {<br>        let _ = Self._printChanges()<br>        <br>        VStack(alignment: .center) {<br><br>            Text(&quot;\(increaseTheCount)&quot;)<br>                .font(.title)<br><br>            Button(&quot;Add&quot;) {<br>                increaseTheCount += 1<br>            }<br>        }<br>        .padding()<br>    }<br>}</pre><p>In the code above, we are displaying the @state property wrapper increaseTheCount in Text view so whenever the increaseTheCount value changes SwiftUI re-render the view of the ContentView.</p><h3>@Bindable property wrapper-</h3><p>It is used to create a two-way connection between a parent and child view’s state. Changes made in the child view affect the state of the parent view, and vice versa. To define it more it is used to create a two-way binding between a property defined in one view and a value defined in another view. This allows changes made in one view to be reflected in another view.</p><p>Lets demonstrate it with code below;</p><pre>@Observable<br>class Batsman {<br>    var isBatting: Bool = false<br>}<br><br>struct Player: View {<br>    @Bindable var isBatsmanOnCrease: Batsman<br><br>    var body: some View {<br>        Toggle(isOn: $isBatsmanOnCrease.isBatting) {<br>            EmptyView()<br>        }<br>    }<br>}<br><br>struct ContentView: View {<br>    @State private var batsman = Batsman()<br><br>    var body: some View {<br>        VStack(alignment: .center) {<br>            Player(isBatsmanOnCrease: batsman)<br>            Text(batsman.isBatting ? &quot;He is on the crease&quot; : &quot;He is not on the crease&quot;)<br>        }<br>        .padding()<br>    }<br>}</pre><p>Here, we did created a class Batsman with a variable isBatting just to confirm whether a batsman is on crease or not. This class is marked with @<a href="https://medium.com/u/38f07ab64248">Observable</a> it allows SwiftUI views to observe changes to the properties of the observed object and update accordingly.</p><p>Now, In parent view ContentView we have a @state property wrapper batsman which is passed to the child view Player. Wherein, In child view Player() we have a variable of @Bindable property wrapper isBatsmanOnCrease and it takes a toggle which takes a bindable argument i.e $isBatsmanOnCrease.isBatting. So whenever the $isBatsmanOnCrease.isBatting values changes it updates the parent view and Text is displayed accordingly depending on its value as shown below.</p><pre>Text(batsman.isBatting ? &quot;He is on the crease&quot; : &quot;He is not on the crease&quot;)</pre><h3>@Environment property wrapper-</h3><p>This property wrappers allows us to handle the global state. It allows you to share data across multiple views in an application by storing it in the environment. Allowing us to pass data down through the view hierarchy without the need for explicit passing through each view. It’s useful for managing global state that needs to be accessed by many different views.</p><p>Points to remember while using @Environment wrapper</p><ol><li>What we pass as argument to it should be <a href="https://medium.com/u/38f07ab64248">Observable</a></li><li>We can pass multiple @environment values</li></ol><p>You can find more on official doc <a href="https://developer.apple.com/documentation/swiftui/environmentvalues">EnvironmentValue</a> where in you can see many defaults environment values available to use by SwiftUI.</p><pre>@Observable<br>class Batsman {<br>    var isBatting: Bool = false<br>}<br><br>struct Player: View {<br>    @Bindable var isBatsmanOnCrease: Batsman<br><br>    var body: some View {<br>        Toggle(isOn: $isBatsmanOnCrease.isBatting) {<br>            EmptyView()<br>        }<br>    }<br>}<br><br>struct Cricket: View {<br>    @Environment(Batsman.self) private var batsman<br><br>    var body: some View {<br>        Player(isBatsmanOnCrease: batsman)<br>    }<br><br>}<br><br>struct ContentView: View {<br>    @Environment(Batsman.self) private var batsman<br><br>    var body: some View {<br>        VStack(alignment: .center) {<br>            Cricket()<br>            Text(batsman.isBatting ? &quot;He is on the crease&quot; : &quot;He is not on the crease&quot;)<br>        }<br>        .padding()<br>    }<br>}</pre><p>Firstly, we have passed .environment(Batsman()) in Window group which is parent to all the view.</p><pre>   WindowGroup <br>        {<br>            ContentView()<br>                .environment(Batsman())<br>        }</pre><p>From above code, we have @Environment variable which is of type Batsman which conforms to @Observable protocol. We pass Batsman in ContentView as @Environment variable which is used in Cricket() view in its body.</p><p>In Cricket view we again have Batsman as @Environment variable which is passed to Player view as a variable argument. In Player view it has a @Bindable variable of type Batsman. So whenever we toggle the value of the Batsman changes changing the @Bindable property which says that we are changing the environment variable which we are passing in <strong>Player(isBatsmanOnCrease: batsman) </strong>of<strong> </strong>Cricket<strong> </strong>view<strong>. </strong>So in the<strong> </strong>ContentView which has environment variable now re-rendered itself and the <strong>Text(batsman.isBatting ? “He is on the crease” : “He is not on the crease”) </strong>gets refreshed.</p><p>Global System wide @Environment usage-</p><p>SwiftUI provides many EnvironmentValues; let look at one of its EnvironmentValues i.e layoutDirection in our example.</p><pre>struct ContentView: View {<br>    @Environment(\.layoutDirection) private var layoutDirection<br><br>    var body: some View {<br>        Spacer()<br>        Text(layoutDirection == .leftToRight ? &quot;Left&quot; : &quot;Right&quot;)<br>        Spacer()<br>    }<br>}</pre><p>Here, SwiftUI provide us with the layout direction whether it is leftToright or rightToleft when we use it in our Text to compare and display the same.</p><p>We can change it as follows;</p><pre>   var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .environment(\.layoutDirection, .rightToLeft)<br>        }<br>    }</pre><h3>Difference Between @Enviroment and @Bindable -</h3><h4>@Environment:</h4><ul><li>The @Environment property wrapper is used to access values that are provided by the environment, such as the color scheme, locale, or accessibility settings.</li><li>It allows you to access environment values without needing to pass them explicitly through your view hierarchy.</li><li>Commonly used to customize the appearance or behavior of views based on the environment in which they are displayed.</li></ul><h4>@Bindable:</h4><ul><li>The @Bindable property wrapper is used to create a custom two-way binding between a property and a view.</li><li>It allows you to define custom bindings for properties that do not natively support binding, such as properties of a Swift class.</li><li>Requires manual implementation of the BindableObject protocol for the object containing the @Bindable property.</li></ul><h3><strong>About </strong><strong>@ObservableObject and </strong><strong>@Published-</strong></h3><p>@ObservableObject is used to declare a class as an observable object, allowing SwiftUI to track changes to its properties. Think of @ObservableObject as a way to keep track of changes in your app&#39;s data. @Published is a property wrapper used inside observable objects to automatically publish changes to any views observing those properties. @Published is like a special tag you put on specific pieces of data to say, &quot;Hey, if this changes, let everyone know!&quot;. View models in SwiftUI are commonly annotated with @ObservableObject. This allows them to hold application state and publish changes to their properties, ensuring that views are updated accordingly. Within observable objects, mark properties that should trigger view updates with @Published. This ensures that changes to these properties are automatically propagated to any views observing them.</p><p><strong>Avoid Overusing </strong><strong>@Published.</strong></p><p>Example of @ObservableObject &amp; @Published usage-</p><ul><li>In a weather app, users expect to see the latest weather conditions without needing to manually refresh the screen.</li><li>You could use @ObservableObject for a WeatherData object that fetches and stores the current weather information.</li><li>Properties like temperature, humidity, and forecast could be marked with @Published.</li><li>As the weather data updates (e.g. due to a new API response), the @Published properties trigger UI updates, ensuring that users always see the most recent weather conditions.</li></ul><p>Connect with me to improve or share many insights on State/ Data Flow Management in SwiftUI iOS:-</p><p><a href="https://www.linkedin.com/in/sachinsabat/">Sachin Sabat - System Engineer - Tata Consultancy Services | LinkedIn</a></p><p>Thank You…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53f53b4b17fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NavigationSplitView for iPad & Larger Device of iPhone in SwiftUI]]></title>
            <link>https://blog.stackademic.com/navigationsplitview-for-ipad-larger-device-iphone-in-swiftui-45d3fb770c8c?source=rss-fad79356b8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/45d3fb770c8c</guid>
            <category><![CDATA[navigation-stack]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[navigationsplitview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sachin Sabat]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 19:32:32 GMT</pubDate>
            <atom:updated>2023-11-09T01:03:50.348Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is all about how to utilise the whole screen effectively using NavigationSplitView</p><p>I have already covered <a href="https://medium.com/@sabatsachin/navigationapi-in-swiftui-1b582f4035aa">NavigationAPI in SwiftUI in the post here</a>. Please do read it as we are going to pick the usage of <strong>NavigationStack &amp; NavigationLink </strong>later in this tutorial.</p><p>To start with, when we use NavigationStack it will cover the whole screen of the iPad/ iPhone pro max as shown in the image below👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EcelPhJHKdcxq_UVWxkKxw.png" /><figcaption>iPad mini takes whole screen size using struct NavigationStack</figcaption></figure><p>To avoid the above case we can split the screen into many views and utilise the whole screen effectively. SwiftUI provides us with <strong>NavigationSplitView</strong> lets explore it.</p><blockquote>NavigationSplitView is a struct that takes in <strong>&lt;Sidebar, Content, Detail&gt;</strong> conforming to View protocol with type conformance of <strong>where Sidebar : View, Content : View, Detail : View</strong></blockquote><pre>public struct NavigationSplitView&lt;Sidebar, Content, Detail&gt; : View where Sidebar : View, Content : View, Detail : View {</pre><p>We can have 2 columns or 3 columns views with the help of NavigationSplitView.</p><p>To create a 2-column navigation split view, use the ``init(sidebar:detail:)`` initializer:</p><p>Refer the SS and the code below to follow;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7cIkiNRS7AwIPijA-AkXhg.png" /><figcaption>2-column navigation split view</figcaption></figure><p>Code for the same-</p><pre>struct ContentView: View {<br>    var body: some View {<br>        NavigationSplitView {<br>            Text(&quot;Sidebar&quot;)<br>        } detail: {<br>            Text(&quot;Detail page for 2 column view&quot;)<br>        }<br><br>    }<br>}</pre><p>To create a 3-column view, use the ``init(sidebar:content:detail:)``</p><p>Refer the SS and the code below to follow;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lkQqKJhA-avTme1TxzHEg.png" /><figcaption>3-column navigation split view</figcaption></figure><p>Code for the same-</p><pre>struct ContentView: View {<br>    var body: some View {<br>        NavigationSplitView {<br>            Text(&quot;Sidebar&quot;)<br>        } content: {<br>            Text(&quot;Content for 3 column view&quot;)<br>        } detail: {<br>            Text(&quot;Detail for 3 column view&quot;)<br>        }<br>    }<br>}</pre><p><strong>How to set interaction between Sidebar and Detail view of NavigationSplitView?</strong></p><p>What we are going to achieve, do find it in the SS below-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCrtYpXnK31f1O_ewVODOg.png" /><figcaption>Interaction of sidebar and detail view</figcaption></figure><pre>// 1<br>enum Games: String, CaseIterable {<br>    case football = &quot;Football&quot;<br>    case cricket = &quot;Cricket&quot;<br>    case hockey = &quot;Hockey&quot;<br>}<br><br>struct GamesListView: View {<br>    // 6<br>    @Binding var games: Games?<br><br>    var body: some View {<br>        // 7<br>        List(Games.allCases, <br>             id: \.self,<br>             selection: $games) { games in<br>            Text(games.rawValue)<br>        }<br>    }<br>}<br>// 8<br>struct GamesDetailView: View {<br>    let games: Games<br>    var body: some View {<br>        Text(games.rawValue)<br>    }<br>}<br><br>struct ContentView: View {<br>    // 3<br>    @State private var games: Games? = .cricket<br><br>    var body: some View {<br>        // 2<br>        NavigationSplitView {<br>            // 4<br>            GamesListView(games: $games)<br>        } detail: {<br>            // 5<br>            GamesDetailView(games: games ?? .cricket)<br>        }<br><br>    }<br>}</pre><p>Point wise breakdown how did we achieve it-</p><ol><li>We did declare a enum of games conforming to CaseIterable protocol</li><li>We created 2-column navigation split view with sidebar and detail view</li><li>We decalred a @State variable to pass in the value of the games selected</li><li>We created a view named GamesListView to display the sidebar list which takes a param of binding value of the games</li><li>We created a view named GamesDetailView to display the game name in the detail page.</li><li>GamesListView declare a property of @Binding so that it can be passed with a @State variable by a view and can be used to refresh the parent view once it gets update. i.e ContentView will refresh once the games value is changed in the GamesListView</li><li>Creates a List with unique id and a param of ‘<strong>selection: $games’ to show the selection bar on the item selected on the sidebar. </strong>Refer the below SS where cricket is highlighted because we have used selection in the List.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*4WeAd0smQc1Kg9dyeppDxQ.png" /></figure><p>8. GamesDetailView takes a property games from content view and displays it on the screen when the sidebar item is selected respectively.</p><p>We can also use <strong>NavigationStack &amp; NavigationLink </strong>on detail page to have further navigation to other pages<strong>.</strong></p><blockquote><strong>Please note NavigationStack &amp; NavigationLink does not work on the sidebar view.</strong></blockquote><p>Making a minor code change on the GamesDetailView from the point number 8 of above code snippet, we will change it with the below code;</p><pre>struct GamesDetailView: View {<br>    let games: Games<br>    var body: some View {<br>        NavigationStack {<br>            NavigationLink(games.rawValue) {<br>                Text(games.rawValue)<br>            }<br>        }<br>    }<br>}</pre><p>Final Output-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRI092IoWlEa4IoQ3Ne7bw.gif" /><figcaption>Final output</figcaption></figure><p><strong>Also read about —</strong> <a href="https://sabatsachin.medium.com/navigationapi-in-swiftui-1b582f4035aa"><strong>NavigationAPI in SwiftUI</strong></a></p><p>GithubLink- <a href="https://github.com/SachinSabat/NavigationSplitView">https://github.com/SachinSabat/NavigationSplitView</a></p><p>I hope you did enjoyed the tutorial.</p><p>Connect with me to improve or share many insights on SwiftUI NavigationSplitView in iOS:-</p><p><a href="https://www.linkedin.com/in/sachinsabat/">Sachin Sabat - System Engineer - Tata Consultancy Services | LinkedIn</a></p><p>Thank You…</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45d3fb770c8c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/navigationsplitview-for-ipad-larger-device-iphone-in-swiftui-45d3fb770c8c">NavigationSplitView for iPad &amp; Larger Device of iPhone in SwiftUI</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NavigationAPI in SwiftUI]]></title>
            <link>https://sabatsachin.medium.com/navigationapi-in-swiftui-1b582f4035aa?source=rss-fad79356b8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b582f4035aa</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[navigationpath]]></category>
            <category><![CDATA[navigation-stack]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Sachin Sabat]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 18:52:42 GMT</pubDate>
            <atom:updated>2023-10-14T18:02:58.429Z</atom:updated>
            <content:encoded><![CDATA[<p>What we will cover in this post- <strong>NavigationStack, NavigationLink, NavigationView, NavigationViewStyle, NavigationDestination, NavigationPath</strong></p><p>To start with, NavigationView &amp; NavigationViewStyle will be deprecated in future version of iOS. So its better to use NavigationStack. Let’s have a look into it.</p><p>Now…<br><strong>What is NavigationStack? — </strong>A view that displays a root view and enables you to present any additional views over the root view.</p><pre>@MainActor<br>struct NavigationStack&lt;Data, Root&gt; where Root : View</pre><p>NavigationStack uses<strong> NavigationLink</strong> to navigate from one view to other view whose definition goes as <strong>A view that controls a navigation presentation.</strong></p><pre>struct NavigationLink&lt;Label, Destination&gt; where Label : View, Destination : View</pre><p>Combining the above NavigationStack &amp; NavigationLink we can write it in many ways as follows;-</p><ol><li><strong>NavigationLink with Title and Destination- </strong>Here it will display the Title text i.e<strong> </strong>“Detail Screen” and on its click it will navigate to DetailView.</li></ol><pre>struct ContentView: View {<br>    var body: some View {<br>        NavigationStack {<br>            NavigationLink(&quot;Detail Screen&quot;) {<br>                DetailView()<br>            }<br>        }<br>    }<br>}<br>struct DetailView: View {<br>    var body: some View {<br>       Text(&quot;Detail Screen&quot;)<br>    }<br>}<br>#Preview {<br>    ContentView()<br>}</pre><p><strong>2. NavigationLink with Destination and Label</strong>. Here, we can add Text, Images, Button as per our requirement in the place of Label to represent our view element.</p><pre>struct ContentView: View {<br>    var body: some View {<br>        NavigationStack {<br>            NavigationLink {<br>                DetailView()<br>            } label: {<br>                Text(&quot;Detail Navigation Test&quot;)<br>                Image(uiImage: .strokedCheckmark)<br>            }<br>        }<br>    }<br>}<br>struct DetailView: View {<br>    var body: some View {<br>        Text(&quot;Detail Screen&quot;)<br>    }<br>}<br>#Preview {<br>    ContentView()<br>}</pre><p><strong>3. NavigationLink with Title and Value.</strong> Here value is the data we need to match and send it to the destination using navigationDestination.</p><p><strong>Value is the composition protocol of (Decodable &amp; Encodable &amp; Hashable)</strong>. Whereas in navigationDestination which has navigationDestination(for: String.self) is a Hashable protocol. refer the code below.</p><pre>import SwiftUI</pre><pre>struct ContentView: View {<br>    var body: some View {<br>        NavigationStack {<br>            NavigationLink(&quot;Detail Navigation Test&quot;, value: &quot;Navigation Destination&quot;)<br>                .navigationDestination(for: String.self) { value in<br>                    DetailView(stringValue: value)<br>                }</pre><pre>        }<br>    }<br>}</pre><pre>struct DetailView: View {<br>    let stringValue: String<br>    var body: some View {<br>        Text(&quot;\(stringValue)&quot;)<br>    }<br>}</pre><pre>#Preview {<br>    ContentView()<br>}</pre><p><strong>4. NavigationLink with Value and Label. </strong>Here the code is slightly different than the 3rd one, the<strong> </strong>navigationDestination will be the Label we declare to. And the Label can be of any protocol as we discussed above in 2nd way.</p><pre>import SwiftUI</pre><pre>struct ContentView: View {<br>    var body: some View {<br>        NavigationStack {<br>            NavigationLink(value: &quot;Navigation Destination&quot;, label: {<br>                Text(&quot;Click me to navigate&quot;)<br>                    .navigationDestination(for: String.self) { value in<br>                        DetailView(stringValue: value)<br>                    }<br>            })<br>        }<br>    }<br>}</pre><pre>struct DetailView: View {<br>    let stringValue: String<br>    var body: some View {<br>        Text(&quot;\(stringValue)&quot;)<br>    }<br>}</pre><pre>#Preview {<br>    ContentView()<br>}</pre><blockquote>The real benefit of navigationDestination is while creating a list. For List <strong>the data should be confirming to Identifiable so it will have unique let id = UUID() </strong>and <strong>must be Hashable too for NavigationLink’s value and navigationDestination(for: ListItems.self) data. Find it in the code below;</strong></blockquote><pre>import SwiftUI</pre><pre>struct ListItems: Identifiable, Hashable {<br>    let name: String<br>    let id = UUID()<br>}</pre><pre>struct ContentView: View {</pre><pre>    let listItems = [<br>        ListItems(name: &quot;Apple&quot;),<br>        ListItems(name: &quot;Samsung&quot;),<br>        ListItems(name: &quot;Nokia&quot;)<br>    ]</pre><pre>    var body: some View {<br>        NavigationStack {<br>            List(listItems) { items in<br>                NavigationLink(items.name, value: items)<br>                    .navigationDestination(for: ListItems.self) { items in<br>                        DetailView(listItems: items)<br>                    }</pre><pre>            }<br>        }<br>    }<br>}</pre><pre>struct DetailView: View {<br>    let listItems: ListItems<br>    var body: some View {<br>        Text(&quot;\(listItems.name)&quot;)<br>    }<br>}</pre><pre>#Preview {<br>    ContentView()<br>}</pre><h3><strong>NavigationStack:-</strong></h3><blockquote>NavigationStack takes 2 param <strong>path which is binding value and root which will return a view</strong>.</blockquote><p>Here the navigation stack with binding values allows us to perform dynamic navigation. when the value with prefix $ changes the navigation destination gets called.</p><pre>struct ContentView: View {<br><br>    @State private var navigationViews = [Int]()<br><br>    var body: some View {<br>        NavigationStack(path: $navigationViews) {<br>            Button(&quot;Navigationstack&quot;) {<br>                navigationViews.append(5)<br>            }<br>        }.navigationDestination(for: Int.self) { destination in<br>            Text(&quot;\(destination)&quot;)<br>        }<br>    }<br>}</pre><p>In above code, when the navigationViews array is changed the navigationDestination gets called. <br><strong>How it works-</strong> The navigation stack now has the view of <strong>Text(“\(destination)”)</strong> in it with the navigationViews appended by value 5 and when it gets pop up the value from the navigationViews gets removed along with the corresponding view too gets removed from the navigation stack.</p><h3>NavigationPath:-</h3><p><strong>What is NavigationPath?-</strong> A type array list of data representing the content of a navigation stack. This means it allows us to add or append objects of any type on already defined type array list i.e NavigationPath. Let us understand it through the code below.</p><pre>import SwiftUI<br><br>//1<br>struct ListItems: Identifiable, Hashable {<br>    let name: String<br>    let id = UUID()<br>}<br>//2<br>class NavigationState: ObservableObject {<br>    @Published var navigation = NavigationPath()<br>}<br>//3<br>struct ContentView: View {<br>    @StateObject private var navigationState = NavigationState()<br>    var body: some View {<br>        NavigationStack(path: $navigationState.navigation) {<br>            //4<br>            BodyView()<br>                .environmentObject(navigationState)<br>        }<br>    }<br>}<br>//5<br>struct BodyView: View {<br>    @EnvironmentObject var navigationState: NavigationState<br>    var body: some View {<br>        //6<br>        Button(&quot;NavigationStack&quot;) {<br>            navigationState.navigation.append(ListItems(name: &quot;navigation path&quot;))<br>        }<br>        .navigationDestination(for: ListItems.self) { destination in<br>            DetailView(listItems: destination)<br>        }<br>        //7<br>        Button(&quot;Int Stack&quot;) {<br>            navigationState.navigation.append(123)<br>        }<br>        .navigationDestination(for: Int.self) { destination in<br>            Text(&quot;\(destination)&quot;)<br>        }<br>    }<br>}<br>//8<br>struct DetailView: View {<br>    let listItems: ListItems<br>    var body: some View {<br>        Text(&quot;\(listItems.name)&quot;)<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><p>We will discuss the above code here-</p><ol><li>We have declared a struct of ListItems which has name and id variable.</li><li>We declared navigation state that confirms to ObservableObject having NavigationPath as its variable. This variable will be of type @Published when ever the value gets changes all the view will get be refreshed and notified.</li><li>We have ContentView which has NavigationStack which takes the param $navigationState in it. <strong>why $navigationState? — </strong>we are binding the value here when the navigationState value changes the respective method will be evoked.</li><li>We have BodyView which has 2 buttons and takes a EnvironmentObject parameter of navigationState</li><li>We have BodyView to have views elements and perform navigation upon values getting changed in the navigationState parameter.</li><li>We declared a button Button(“NavigationStack”) which takes a navigationDestination(for: ListItems.self), so when we append any value of ListItems on to navigationState the navigationDestination takes the ListItems value and send it to the destination i.e DetailView</li><li>We declared a Button(“Int Stack”) which takes a navigationDestination(for: Int.self), so when we append any Int values on to navigationState the navigationDestination takes the Int value and send it to the destination. In our case it is a simple Text(“\(destination)”) showing the Int value.</li><li>Here we defined DetailView which takes ListItems as param and show the value once we append any ListItems on to navigationState as on step 6 from the above code.</li></ol><p>This way we can have different types of object confirmation to navigationDestination and perform navigation using NavigationPath array.</p><p>Connect with me to improve or share many insights on SwiftUI Navigation Stack in iOS:-</p><p><a href="https://www.linkedin.com/in/sachinsabat/">Sachin Sabat - System Engineer - Tata Consultancy Services | LinkedIn</a></p><p>Thank You…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b582f4035aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting Date and Time to a particular TimeZone in Swift iOS]]></title>
            <link>https://sabatsachin.medium.com/converting-date-and-time-to-a-particular-timezone-c98588551794?source=rss-fad79356b8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c98588551794</guid>
            <category><![CDATA[datecomponent]]></category>
            <category><![CDATA[timezone]]></category>
            <category><![CDATA[dateformatter]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sachin Sabat]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 17:30:38 GMT</pubDate>
            <atom:updated>2023-09-18T12:07:27.176Z</atom:updated>
            <content:encoded><![CDATA[<p>Three main structs which are pillars of iOS date time conversion are:-</p><ol><li>Date- The Date structure provides methods for comparing dates, calculating the time interval between two dates, and creating a new date from a time interval relative to another date. <em>swift syntax-</em> Date()</li><li>Calendar- A definition of the relationships between calendar units (such as eras, years, and weekdays) and absolute points in time, providing features for calculation and comparison of dates. You can use Calendar.current to get the user’s current calendar.</li><li>DateComponents- It is used to specify a date by providing the temporal components that make up a date and time in a particular calendar: hour, minutes, seconds, day, month, year, and so on.</li></ol><p>Apple’s framework deals with Date and Calendar to fetch time in a particular TimeZone. But, for a user it should be in textual representation so that he can read it clearly. For which we use DateFormatter.</p><h3>DateFormatter:</h3><p>Introducing class DateFormatter which converts between dates and their textual representations. It also comes up with different style that we can provide it abruptly as follows:-</p><pre>let dateFormatter = DateFormatter()<br>dateFormatter.dateStyle = .medium<br>dateFormatter.timeStyle = .none</pre><p>Both dateStyle and timeStyle of Dateformatter are declared as a variable and various styles provided are:-</p><p><strong>Type — </strong>dateStyle — timeStyle</p><p>full — Monday, June 22, 2022 AD — 3:30:32 PM Indian Standard Time</p><p>long — November 23, 2022 — 3:30:32 PM IST</p><p>medium — Nov 23, 2022 — 3:30:32 PM</p><p>short — 11/12/22 — 3:30 PM</p><p>It also has a variable <strong>dateFormat</strong> which is declared as a string and accept different type of string format to show a particular date in user readable format. To take an example, if we want to display <strong>20 Dec ’21, 02:30 PM (GMT+5:30)</strong> than we will specify as follows-</p><pre>let dateFormatter = DateFormatter()<br>dateFormatter.dateFormat = &quot;dd MMM ’yy, h:mm a&quot;</pre><p>Various type of format to display in required user readable format are as follows-</p><p><strong>Type — Format</strong></p><p>Era — G (AD), GGGG (Anno Domini)</p><p>Year — y (2018), yy (18), yyyy (2018)</p><p>Month — M, MM, MMM, MMMM, MMMMM</p><p>Day of month — d, dd</p><p>Day name of week — E, EEEE, EEEEE, EEEEEE</p><p>It also has <strong>timeZone</strong> as a variable which is of type <strong>struct TimeZone</strong>. We will go deeper into it in further sections.</p><pre>let dateFormatter = DateFormatter()<br>dateFormatter.timeZone = .current</pre><p>What if we want to change the date shown in localised format in that particular language/ region. We can handle it with the variable <strong>locale</strong> which is of type <strong>struct Locale</strong>.</p><pre>let dateFormatter = DateFormatter()<br>dateformatter.locale = Locale(identifier: &quot;fr&quot;)</pre><p>which will display it in french language. Identifier in Locale is ISO 639–1 defined abbreviations for languages.</p><h3>TimeZone:</h3><p>It defines the behavior of a time zone. It’s values represent geopolitical regions, which has names for these regions. This values also represent a temporal offset, either plus or minus, from Greenwich Mean Time (GMT) and an abbreviation (such as PST for Pacific Standard Time). TimeZone provides two static functions to get time zone values: current and autoupdatingCurrent.</p><p><strong>How to convert a particular date string to current location date time in readable format?</strong></p><p>Suppose we have a string <strong>“07/10/2021 23:59:00”</strong> that we want to show as <strong>“Oct, 07 2021 (11:59 PM)”. </strong>We<strong> </strong>need to covert the string into Date, so for doing this we need to pass a proper dateFormat of it else the conversion won’t be proper and it will be show the current date.</p><pre>let dateString = &quot;07/10/2021 23:59:00&quot;<br>let dateFormatter = DateFormatter()<br>dateformatter.dateFormat = &quot;dd/MM/yyyy HH:mm:ss&quot; dateformatter.timeZone = TimeZone.current <br>dateFormatter.date(from: dateString)</pre><p>For timeZone we can pass TimeZone(identifier: “America/New_York”) or TimeZone(abbreviation: “fr”). The above method will convert string to date which will give proper formatting of date from a string. Now we can change the Date to any readable string format we want. Now to convert the Date back to our readable format <strong>“Oct, 07 2021 (11:59 PM)” </strong>we will be using the same methods just will be changing the dateFormat and last method i.e dateFormatter.string(from: date).</p><pre>let dateFormatter = DateFormatter()<br>dateformatter.dateFormat = &quot;MMM, dd yyyy (h:mm a)&quot;<br>dateformatter.timeZone = TimeZone.current <br>dateFormatter.string(from: date)</pre><p>Before moving ahead for date conversion lets go through the DST concepts as this will be useful in abbreviation part of timeZone.</p><h3>DST: — What is Daylight Saving Time (DST)?</h3><p><a href="https://www.civilsdaily.com/news/what-is-daylight-saving-time-dst/"><strong>What is Daylight Saving Time (DST)?</strong></a><br><a href="https://www.civilsdaily.com/news/what-is-daylight-saving-time-dst/"><em>From UPSC perspective, the following things are important : Prelims level : Daylight Saving Time (DST), Equinoxes Mains…</em>www.civilsdaily.com</a></p><p>Please read the article to get to know why we need to handle the DST time format too. Just to walk over the concept; We can conclude DST as it is the practise of resetting clocks ahead by an hour in spring, and behind by an hour in autumn (or fall).</p><p><strong>If we want to show the abbreviation of timeZone like “Oct, 07 2021 (11:59 PM) IST”. </strong>we use a function shown below-</p><pre>let timezone:TimeZone = TimeZone.current<br>if timezone.isDaylightSavingTime() {<br>timezone.localizedName(for: .daylightSaving, locale: .autoupdatingCurrent)<br>} else {<br>timezone.localizedName(for: .standard, locale: .autoupdatingCurrent) ?? &quot;&quot;<br>}</pre><p><strong>isDaylightSavingTime</strong> function returns a Boolean value that indicates whether the receiver is in daylight saving time at a given date.</p><pre>func isDaylightSavingTime(for date: Date = Date()) -&gt; Bool</pre><p>Also, Code for getting Identifier and abbreviation.</p><pre>let timeZone = TimeZone.current<br>let dateFormatter = DateFormatter()<br>let Identifier = dateFormatter.timeZone.identifier <strong>o/p- Asia/kolkatta</strong><br>let abbreviation = dateFormatter.timeZone.abbreviation() ?? “” <strong>o/p- GMT+10</strong></pre><h3>DateComponents:</h3><p>DateComponents represents a date in terms of units (such as year, month, day, hour, and minute)</p><p>The following example shows the date and time I ran the programme.</p><pre>let dateComponents = Calendar.current.dateComponents(in: .current, from: Date())<br>let year = dateComponents.year // 2020<br>let month = dateComponents.month // 11<br>let weekday = dateComponents.weekday // 4<br>let hour = dateComponents.hour // 10<br>let minute = dateComponents.minute // 30<br>let second = dateComponents.second // 9<br>let date = dateComponents.date // Nov 4, 2020 at 10:30 AM</pre><p><strong>Epoch Calculation Approach:</strong></p><p>Timezone conversion is nothing but adding or subtracting timezone offset from the GMT date. Eg. The timezone offset for India is +0530 which means just need to add +5:30 hours in the GMT date.</p><p>Now we understood how DateFormatter helps us to convert the GMT date to the local timezone. Let’s try an alternative way to convert the timezone with Epoch Calculation.</p><p>Epoch timezone conversion is very simple. Here the addition of timezone offset from epoch time gives us the date and time according to the current timezone.</p><pre>var date = Date()<br>let timezoneOffset =  TimeZone.current.secondsFromGMT()<br>let epochDate = date.timeIntervalSince1970<br>let timezoneEpochDate = (epochDate + Double(timezoneOffset))<br>let dateWithCurrentTimezone = Date(timeIntervalSince1970: timezoneEpochDate)</pre><p>Let’s dissect the above code.</p><p><strong>TimeZone.current.secondsFromGMT() </strong><br>It gives the current timezone offset in seconds. <br>Eg. If our timezone offset is (+0530) for IST which is +5:30 hours so it converts and returns the offset into the seconds (Which are +19800 seconds)</p><p><strong>date.timeIntervalSince1970</strong><br>This converts a date to epoch time.</p><p><strong>(epochDate + Double(timezoneOffset))</strong><br>Here timezone offset is added to the epoch date.</p><p><strong>Date(timeIntervalSince1970: timezoneEpochDate)</strong><br>The Date struct handles the conversion of epoch time interval to <strong>Date</strong>. So here we get the date and time with the current timezone.</p><p>This is all about Date and Time usage in iOS by using all components provided by swift to convert Date to String and vice-versa</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c98588551794" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Threads in iOS…]]></title>
            <link>https://sabatsachin.medium.com/what-are-threads-in-ios-4e926dd132a5?source=rss-fad79356b8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e926dd132a5</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[gcd]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sachin Sabat]]></dc:creator>
            <pubDate>Sun, 28 Mar 2021 20:26:11 GMT</pubDate>
            <atom:updated>2021-03-29T08:58:16.228Z</atom:updated>
            <content:encoded><![CDATA[<p>Had enough of article on GCD and Queue management; let’s not dive into codes but let us summarise all about threads in iOS.</p><p>As said <strong>Threading happens inside the processor to prioritise things in our application. </strong>Depending on the processor the number of threads are allocated to a <strong>particular process. </strong>A<strong> </strong>single core processor will consist of a single thread having its own section of physical memory associated with it performing context switching over task. Depending upon the core; a process can have one or more threads (Multithreaded — uses Concurrency &amp; Parrallelism).</p><h3>Wait a minute! … What is a process?</h3><p>Process is your application running in active state executing instruction at run time. Instructions are of assembly format which understands in binary digits; known as <strong>bits</strong> having two values 0 &amp; 1. They can be grouped as 4, 8, 16, 32 or 64. <strong>Also, 1 byte = 8 bit.</strong></p><pre><strong>Swift uses 64-bit numbers</strong>. To take an example of, the standard Int type is of 64 bits. Having the least significant bit(LSB) to the right side and the most significant bit(MSB) to the left side.</pre><p>The LSB &amp; MSB depends upon the <strong>endianness </strong>of an<strong> </strong>architecture. Whereas, endianness are of two type namely;</p><ul><li>big-endian — MSB stored in lowest memory address</li><li>little-endian — LSB stored in lowest memory address</li></ul><blockquote>Apple’s own A processors is little-endian</blockquote><p>While using swift standard library we don’t need to worry about the endianness but while working with low-level C library API we take into consideration as we deal with pointers towards register in memory location.</p><p>Lets describe it in the POSIX thread diagram:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*fCuzTojSqkUJgfBZYRxe_w.gif" /><figcaption>1. A Process having more than one thread in its memory</figcaption></figure><p>From Image 1 above; A thread consist of a Stack, collection of register with unique identifier, also known as properties.</p><p>In iOS, a process or application can consists of one or more threads. The operating system scheduler manages the threads independently of each other. Each thread can execute concurrently, but it’s up to the system to decide if this happens, when this happens, and how it happens.- Ray Wenderlich</p><p>It may look great to have several threads in an app but all comes with a cost and takes time while it gets created. Coming to the cost, The main thread has a fix stack size of 1MB which initiallly uses some space but can grow till 1MB depending on its usage and any other secondary thread has size of 512KB by default. One can change its size before starting the thread with minimum size of 16KB (always in a multiple of 4KB)</p><blockquote>Max thread limit in iOS app is 64</blockquote><p>To start with, <strong>The Main thread </strong>in iOS which is the starting point in any app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i6Geuu9lrjtJK62fZWcf_g.jpeg" /><figcaption>2. Sequence diagram of App delegate lifecycle</figcaption></figure><p>As shown in image no 2. After the <em>&lt;&lt;creation&gt;&gt;8:</em> off Runloop; getting to <em>9:Run</em>, drawing the current screen if needed denotes the <strong>starting point of the Main Thread. </strong>This Main Thread is responsible only to update the UI elements rest all heavy weightage task should be done on the <strong>background thread.</strong></p><p>We can always check on which thread we are on using<strong><em> </em></strong>Thread.current<strong><em> </em></strong>and main thread using code<strong><em> </em></strong>Thread.current.isMainThread.</p><p>We can have a look at the number threads as shown in image 3 below; Run Application -&gt; Show the debug navigator -&gt; Pause the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*vPDW6qIlpo3VHxwj9bniYg.png" /><figcaption>3. Threads available</figcaption></figure><h3><strong>Summarising GCD on thread -</strong></h3><p><strong>GCD (FIFO queues)</strong> is built on top of threads. Under the hood it manages a shared thread pool — Ray Wenderlich<br>All task controlled by GCD are on pool of threads which are managed by the system. <strong>Serial queue</strong> has one thread associated with it whereas <strong>Concurrent queue</strong> uses many thread available by the system. But, if the thread share the same process, sharing same address space which can read &amp; write to same shared resource will lead to <strong>Race condition. </strong>One need to be careful while handling it as read &amp; write are two separate task which depends on CPU clock cycles; wherein one tick of the clock allows one task at a time to execute. We can solve this by using <strong>Thread Barrier</strong> that when called to write a task completes before moving forward to read a task but after finishing all the read task that was submitted before a write task.</p><p>Connect with me to improve or share many insights on threads in iOS:-</p><p><a href="https://www.linkedin.com/in/sachinsabat/">Sachin Sabat - System Engineer - Tata Consultancy Services | LinkedIn</a></p><p>References:- <a href="https://www.w3.org/People/Frystyk/thesis/multithread.html">https://www.w3.org/People/Frystyk/thesis/multithread.html</a></p><p><strong>We will dive into codes in the next article…<em>COMING SOON!</em></strong></p><p><strong>Thank you…</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e926dd132a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detect JailBreak Device in Swift 5 (iOS) programatically]]></title>
            <link>https://sabatsachin.medium.com/detect-jailbreak-device-in-swift-5-ios-programatically-da467028242d?source=rss-fad79356b8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/da467028242d</guid>
            <category><![CDATA[swift-5]]></category>
            <category><![CDATA[mobile-security]]></category>
            <category><![CDATA[jailbreak]]></category>
            <category><![CDATA[jailbreak-ios-13-5]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sachin Sabat]]></dc:creator>
            <pubDate>Sat, 01 Aug 2020 20:41:42 GMT</pubDate>
            <atom:updated>2026-03-06T20:43:46.656Z</atom:updated>
            <content:encoded><![CDATA[<h3>Detect Jailbreak device iOS swift 2026</h3><p>Detect Jailbreak device in iOS/ Swift programmatically | Avoid Attackers to intrude in your application by all means possible in a single page| Supported to Swift (world first Protocol Oriented Language 🤘)</p><blockquote>There are many ways to bypass the JailBreak implementation namely Liberty- Lite, A- Bypass, KernByPass (kernel level root change using MTerminal) from the Cydia Directory</blockquote><h4><strong>But, we will detect it by all means possible and successfully pass our security check list for our application.</strong></h4><p><strong>Github Link:- </strong><a href="https://github.com/SachinSabat/CheckJailBreakDevice"><strong>https://github.com/SachinSabat/CheckJailBreakDevice</strong></a></p><h3>Why JailBreak a device?</h3><p>— Attackers JailBreak a device to get unrestricted access (root privileges)of the application, making <strong>it accessible to source code, and crucial files</strong> of the application. All the application downloaded from the app store is downloaded in <em>/var/mobile/Applications/</em>directory.</p><p>So in JailBreak Device there is always a <strong>Cydia app</strong> Installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*HmZO00Shd_mu98mMtufIAw.png" /></figure><h3>We will Identify a JailBreak device in 5 ways -</h3><ol><li><strong>We will check if we can open Cydia App:-</strong></li></ol><pre>func isCydiaAppInstalled() -&gt; Bool {<br>    return UIApplication.shared.canOpenURL(URL(string: &quot;cydia://&quot;)!)<br>}</pre><p>Add this in your plist file-</p><pre><strong>&lt;key&gt;</strong>LSApplicationQueriesSchemes<strong>&lt;/key&gt;</strong></pre><pre><strong>&lt;array&gt;</strong></pre><pre><strong>&lt;string&gt;</strong>cydia<strong>&lt;/string&gt;</strong></pre><pre><strong>&lt;/array&gt;</strong></pre><p>Call this function from <strong>didFinishLaunchingWithOptions and applicationDidBecomeActive</strong>, This works 90% for every application which detects Cydia app in rooted device, If in case the root directory is being changed then we can go by 2nd option for JailBreak detection.</p><p><strong>2. Detecting File from the System:-</strong></p><p>Many files are created when we JailBreak a device. Detecting it in the file system method will let one know if the device is JailBroken or not. I have list down important files to check in the file system.</p><pre>               [&quot;/private/var/lib/apt&quot;,<br>                &quot;/Applications/Cydia.app&quot;,<br>                &quot;/private/var/lib/cydia&quot;,<br>                &quot;/private/var/tmp/cydia.log&quot;,<br>                &quot;/Applications/RockApp.app&quot;,<br>                &quot;/Applications/Icy.app&quot;,<br>                &quot;/Applications/WinterBoard.app&quot;,<br>                &quot;/Applications/SBSetttings.app&quot;,<br>                &quot;/Applications/blackra1n.app&quot;,<br>                &quot;/Applications/IntelliScreen.app&quot;,<br>                &quot;/Applications/Snoop-itConfig.app&quot;,<br>                &quot;/usr/libexec/cydia/&quot;,<br>                &quot;/usr/sbin/frida-server&quot;,<br>                &quot;/usr/bin/cycript&quot;,<br>                &quot;/usr/local/bin/cycript&quot;,<br>                &quot;/usr/lib/libcycript.dylib&quot;,<br>                &quot;/bin/sh&quot;,<br>                &quot;/usr/libexec/sftp-server&quot;,<br>                &quot;/usr/libexec/ssh-keysign&quot;,<br>                &quot;/Library/MobileSubstrate/MobileSubstrate.dylib&quot;,<br>                &quot;/bin/bash&quot;,<br>                &quot;/usr/sbin/sshd&quot;,<br>                &quot;/etc/apt&quot;,<br>                &quot;/usr/bin/ssh&quot;,<br>                &quot;/bin.sh&quot;,<br>                &quot;/var/checkra1n.dmg&quot;,<br>                &quot;/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist&quot;,<br>                &quot;/System/Library/LaunchDaemons/com.ikey.bbot.plist&quot;,<br>                &quot;/Library/MobileSubstrate/DynamicLibraries/LiveClock.plist&quot;,<br>                &quot;/Library/MobileSubstrate/DynamicLibraries/Veency.plist&quot;,<br>                &quot;/etc/apt/sources.list.d/electra.list&quot;,<br>                &quot;/etc/apt/sources.list.d/sileo.sources&quot;,<br>                &quot;/.bootstrapped_electra&quot;,<br>                &quot;/usr/lib/libjailbreak.dylib&quot;,<br>                &quot;/jb/lzma&quot;,<br>                &quot;/.cydia_no_stash&quot;,<br>                &quot;/.installed_unc0ver&quot;,<br>                &quot;/jb/offsets.plist&quot;,<br>                &quot;/usr/share/jailbreak/injectme.plist&quot;,<br>                &quot;/etc/apt/undecimus/undecimus.list&quot;,<br>                &quot;/var/lib/dpkg/info/mobilesubstrate.md5sums&quot;,<br>                &quot;/jb/jailbreakd.plist&quot;,<br>                &quot;/jb/amfid_payload.dylib&quot;,<br>                &quot;/jb/libjailbreak.dylib&quot;,<br>                &quot;/usr/libexec/cydia/firmware.sh&quot;,<br>                &quot;/var/lib/cydia&quot;,<br>                &quot;/private/var/Users/&quot;,<br>                &quot;/var/log/apt&quot;,<br>                &quot;/private/var/stash&quot;,<br>                &quot;/private/var/cache/apt/&quot;,<br>                &quot;/private/var/log/syslog&quot;,<br>                &quot;/Applications/FakeCarrier.app&quot;,<br>                &quot;/Applications/MxTube.app&quot;,<br>                &quot;/Applications/SBSettings.app&quot;,<br>                &quot;/private/var/mobile/Library/SBSettings/Themes&quot;,<br>                &quot;/Library/MobileSubstrate/CydiaSubstrate.dylib&quot;]</pre><p>Create a function that checks all those files in the root directory. Like shown below;</p><pre>func isJailBrokenFilesPresentInTheDirectory() -&gt; Bool {<br>let fm = FileManager.default<br>if(fm.fileExists(atPath: &quot;/private/var/lib/apt&quot;)) || (fm.fileExists(atPath: &quot;/Applications/Cydia.app&quot;))<br>{<br>    // This Device is jailbroken<br>      return true<br>} else {<br>    // Continue the device is not jailbroken<br>      return false<br> }<br>}</pre><p>Other method is to try to write into system files.</p><p><strong>3. Writing into System Files:-</strong></p><p>All application are being given the root privilege and can modify the files outside the sandbox. If the app can write to files outside its sandbox then the app is being run on a JailBreak device.</p><pre><br>static func canEditSandboxFilesForJailBreakDetecttion() -&gt; Bool {<br>let jailBreakTestText = &quot;Test for JailBreak&quot;<br>do {<br>try jailBreakTestText.write(toFile:&quot;/private/jailBreakTestText.txt&quot;, atomically:true, encoding:String.Encoding.utf8)<br>  return true<br>} catch {<br>  return false<br>}<br>}</pre><p>GitHub Link:- <a href="https://github.com/SachinSabat/CheckJailBreakDevice">https://github.com/SachinSabat/CheckJailBreakDevice</a></p><p><strong>4. Detecting suspicious library and Frida/ Dopamine Environment variables:-</strong></p><p><strong><em>To check suspicious library</em>-</strong></p><pre> private func isSuspiciousLibraryLoaded() -&gt; Bool {<br>        // Array of known suspicious libraries or patterns to check for<br>        let suspiciousLibraryPatterns = [<br>            &quot;frida&quot;,        // Example: Frida related libraries<br>            &quot;libinjector&quot;   // Example: Other common library names<br>        ]<br><br>        // It returns the total number of dynamic libraries (images) currently loaded into the process. This count is used to iterate through the libraries.<br>        let libraryCount = _dyld_image_count()<br>            // This loop iterates over the range from 0 to libraryCount - 1, accessing each loaded library by its index.<br>            for index in 0..&lt;libraryCount {<br>                //  It retrieves the name of the library at the specified index. Since this function returns an optional UnsafePointer&lt;CChar&gt;?, you use guard let to safely unwrap the optional. If the name cannot be retrieved (i.e., imageName is nil), the loop continues to the next index.<br>                guard let imageName = _dyld_get_image_name(index) else {<br>                    continue<br>                }<br>                // Convert the C string to a Swift string<br>                let libraryName = String(cString: imageName)<br><br>                // This nested loop iterates over each pattern in suspiciousLibraryPatterns. It converts both libraryName and pattern to lowercase to perform a case-insensitive comparison.<br>                for pattern in suspiciousLibraryPatterns {<br>                    if libraryName.lowercased().contains(pattern.lowercased()) {<br>                        return true<br>                    }<br>                }<br>            }<br><br>            return false<br>    }</pre><p>It aims to detect if any dynamically loaded libraries contain names matching known suspicious patterns. Needs adjustment to properly retrieve and check library names.</p><p><strong>Steps</strong>:</p><ol><li>Define suspicious patterns.</li><li>Get the count of loaded libraries.</li><li>Iterate through each library, obtain its name, and check against patterns.</li><li>Return true if a match is found, otherwise return false.</li></ol><p><strong><em>To check Frida environment</em></strong><em> </em><strong><em>variables</em></strong><em>-</em></p><pre>    private func isFridaEnvironmentVariablePresent() -&gt; Bool {<br>        // This array contains names of environment variables that are commonly set by Frida or related tools.<br>        let environmentVariables = [&quot;FRIDA&quot;, &quot;FRIDA_SERVER&quot;]<br>        // Fetches the current environment variables of the process.<br>        let environment = ProcessInfo.processInfo.environment<br>        // Iterates over the list of environment variables you are interested in.<br>        for variable in environmentVariables {<br>            // Checks if the environment variable is set (i.e., not nil).<br>            if environment[variable] != nil {<br>                return true<br>            }<br>        }<br>        return false<br>    }</pre><p>Checks if specific environment variables, which might indicate the presence of Frida, are set in the current process.</p><p><strong>Steps</strong>:</p><ol><li>Define a list of environment variable names to check.</li><li>Fetch the current environment variables of the process.</li><li>Iterate through the list of suspicious environment variables.</li><li>Return true if any of these variables are found, otherwise return false.</li></ol><p><strong>GitHub Link:- </strong><a href="https://github.com/SachinSabat/CheckJailBreakDevice"><strong>https://github.com/SachinSabat/CheckJailBreakDevice</strong></a></p><p><strong>5. Calling System API functions:-</strong></p><p>In a sandbox environment which has root privilege does not allow call to system API. We can make a call to those system API and recognise if we are running our app in JailBroken device.</p><ul><li><em>Fork() API call -</em></li></ul><pre>let pid = fork()<br>if(!pid)<br>{<br>  return true<br>}<br>else if(pid &gt;= 0)<br>{<br>  return false<br>}</pre><ul><li><em>System() API call -</em></li></ul><pre>let system= system()<br>if(system == 1)<br>{<br>  return true<br>}<br>else if(system == 0)<br>{<br>  return false<br>}</pre><p>This both fucntion call will make our job done to check for JailBreak device. Calling <strong>_dyld_image_name </strong>function takes a lot of time to execute and give us the result, which won’t be suitable in a application to call and execute for JailBreak detection.</p><p>In all above, function calls do check for <strong>if(TARGET_IPHONE_SIMULATOR)</strong> <strong>|| arch(i386) || arch(x86_64)</strong> and return false accordingly. All three are checks to identify if the app is being run on simulator.</p><p>Call the JailBreak function from <strong>didFinishLaunchingWithOptions</strong> and <strong>applicationDidBecomeActive. </strong>Also, we can call from the <strong>viewDidLoad()</strong> function of important ViewController page.</p><p>Exit the application if found on JailBroken device by two ways:-</p><pre>// Exit the app (Recommended first option)<br>UIControl().sendAction(#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)<br>---------------------- OR ------------------------<br>exit(-1)</pre><p><strong>GitHub Link:- </strong><a href="https://github.com/SachinSabat/CheckJailBreakDevice"><strong>https://github.com/SachinSabat/CheckJailBreakDevice</strong></a></p><p>Let me know if any problem faced during code implementation.</p><p><a href="https://www.linkedin.com/in/sachinsabat/">Sachin Sabat - System Engineer - Tata Consultancy Services | LinkedIn</a></p><p>Reference:- <a href="https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/jailbreak-detection-methods/">https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/jailbreak-detection-methods/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da467028242d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>