<?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 Mohit Bhalla on Medium]]></title>
        <description><![CDATA[Stories by Mohit Bhalla on Medium]]></description>
        <link>https://medium.com/@mohit-bhalla?source=rss-b9a39631351a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WPFSLU_l8EK0XW6IQlDUHw.jpeg</url>
            <title>Stories by Mohit Bhalla on Medium</title>
            <link>https://medium.com/@mohit-bhalla?source=rss-b9a39631351a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 09:39:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohit-bhalla/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[Unit Testing with Reflection]]></title>
            <link>https://mohit-bhalla.medium.com/unit-testing-with-reflection-5a9bbb0176f0?source=rss-b9a39631351a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a9bbb0176f0</guid>
            <category><![CDATA[mirror-unit-test]]></category>
            <category><![CDATA[unit-mirror-reflection]]></category>
            <category><![CDATA[reflections]]></category>
            <category><![CDATA[ios-unit-test]]></category>
            <dc:creator><![CDATA[Mohit Bhalla]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 12:59:09 GMT</pubDate>
            <atom:updated>2026-04-15T12:59:09.284Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is Reflection?</strong></p><p><strong>Reflection</strong> means:</p><p><em>Inspecting the structure of an object at runtime.</em></p><p>In simple words, your code can <strong>look inside an object</strong> and see its properties.</p><p><strong>In Swift:</strong></p><p>Swift provides Mirror for reflection.</p><pre>let mirror = Mirror(reflecting: object)</pre><p>You can use it to:</p><ul><li>Read properties</li><li>Access internal/private values</li><li>Understand object structure</li></ul><p><strong>2. Why Write Unit Test Cases?</strong></p><p>Unit tests help you ensure your code works correctly.</p><p><strong>Benefits:</strong></p><ul><li>Catch bugs early</li><li>Prevent breaking existing code</li><li>Make refactoring safe</li><li>Improve code quality</li></ul><p><strong>3. Reflection in Unit Testing</strong></p><p>Normally, <strong>private properties are not accessible</strong> in tests.</p><p>But reflection allows you to inspect them without changing access levels.</p><p>This is useful when:</p><ul><li>You don’t want to expose internal data</li><li>You’re testing legacy or closed code</li></ul><p><strong>4. Simple Example</strong></p><pre>class SampleManager {<br>  private var items: [String] = [&quot;A&quot;, &quot;B&quot;]<br>  private var isActive: Bool = true<br>}</pre><p><strong>Test Using Reflection</strong></p><pre>import XCTest<br>class SampleManagerTests: XCTestCase {<br>  func testItemsUsingReflection() {<br>    let manager = SampleManager()<br>    let mirror = Mirror(reflecting: manager)<br>    var items: [String]?<br>    for child in mirror.children {<br>      if child.label == &quot;items&quot; {<br>        items = child.value as? [String]<br>      }<br>    }<br>    XCTAssertEqual(items, [&quot;A&quot;, &quot;B&quot;])<br>   }<br>}</pre><p><strong>Another Test</strong></p><pre>func testIsActiveFlag() {<br>    let manager = SampleManager()<br>    let mirror = Mirror(reflecting: manager)<br>    var isActive: Bool?<br>    for child in mirror.children {<br>      if child.label == &quot;isActive&quot; {<br>        isActive = child.value as? Bool<br>      }<br>    }<br>    XCTAssertTrue(isActive ?? false)<br>}</pre><p><strong>5. When to Use Reflection?</strong></p><p><strong>Use it when:</strong></p><ul><li>You need to check private data</li><li>You cannot modify the original class</li></ul><p>❌<strong> Avoid it when:</strong></p><ul><li>You can test via public methods</li><li>You want stable and maintainable tests</li></ul><p><strong>6. Best Practice</strong></p><ul><li>Prefer testing <strong>behavior</strong>, not internal state</li><li>Use reflection only when needed</li><li>Keep tests simple and readable</li></ul><p>🎯<strong> Summary</strong></p><ul><li>Reflection = inspect object at runtime</li><li>Unit tests = ensure correctness</li><li>Reflection helps test private properties</li><li>Use it carefully</li></ul><p>KEEP CODING!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a9bbb0176f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Your tvOS App with Top Shelf Integration]]></title>
            <link>https://mohit-bhalla.medium.com/enhancing-your-tvos-app-with-top-shelf-integration-98e40d2cc01e?source=rss-b9a39631351a------2</link>
            <guid isPermaLink="false">https://medium.com/p/98e40d2cc01e</guid>
            <category><![CDATA[ott-app-development]]></category>
            <category><![CDATA[top-shelf-tvos]]></category>
            <category><![CDATA[top-shelf-integration]]></category>
            <category><![CDATA[tvos-ott-app]]></category>
            <category><![CDATA[apple-tv-app-design]]></category>
            <dc:creator><![CDATA[Mohit Bhalla]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 08:55:37 GMT</pubDate>
            <atom:updated>2025-10-09T08:55:37.807Z</atom:updated>
            <content:encoded><![CDATA[<p>Apple TV apps have a unique opportunity to showcase content right on the Home screen using <strong>Top Shelf integration</strong>. The Top Shelf allows your app to highlight featured content, engage users, and drive more interaction even before they launch your app. In this blog, we’ll explore what Top Shelf is, how it works, and how to implement it in your tvOS app.</p><h4>What is Top Shelf?</h4><p>Top Shelf is the area at the top of the Apple TV Home screen. Apps can display content here in two ways:</p><ol><li><strong>Static Top Shelf</strong> – Displays fixed images. Ideal for apps that don’t update frequently.</li><li><strong>Dynamic Top Shelf</strong> – Displays live content fetched from your app. Ideal for media apps showcasing movies, shows, or other dynamic content.</li></ol><p>Apple recommends using <strong>Dynamic Top Shelf</strong> for OTT and entertainment apps to keep content fresh and engaging.</p><h4>Configuring Your App for Top Shelf</h4><ol><li>Open your project in Xcode.</li><li>Select your <strong>tvOS target → Capabilities → Top Shelf</strong>.</li><li>Choose the <strong>Top Shelf style</strong>:</li></ol><ul><li><strong>Inset</strong> – Single row, centered display</li><li><strong>Header</strong> – Multiple items grouped under a header</li></ul><h4>Creating a Top Shelf Extension</h4><ol><li>Go to <strong>File → New → Target → tvOS → Top Shelf Extension</strong>.</li><li>Name your extension (e.g., MyAppTopShelf).</li><li>Xcode generates a new target with a TopShelfProvider.swift for dynamic content or TopShelfViewController.swift for static content.</li></ol><h4>Dynamic Top Shelf Implementation</h4><p>Dynamic Top Shelf uses the TVServices framework. Each piece of content is represented by a TVContentItem.</p><p>Here’s an example:</p><pre>import TVServices<br><br>class TopShelfProvider: NSObject, TVTopShelfProvider {<br>    <br>    var topShelfItems: [TVContentItem] {<br>        let item = TVContentItem(identifier: &quot;1&quot;, container: nil)<br>        item.title = &quot;Featured Movie&quot;<br>        item.imageShape = .poster<br>        item.imageURL = URL(string: &quot;https://example.com/movie-poster.jpg&quot;)<br>        return [item]<br>    }<br>}</pre><p>Key points:</p><ul><li>identifier – Unique ID for each content item</li><li>title – Displayed title</li><li>imageURL – Image for the preview</li><li>imageShape – .poster (vertical) or .square</li></ul><h4>Static Top Shelf Implementation</h4><p>For apps with static content:</p><ol><li>Place images in the <strong>TopShelfImages folder</strong> inside the extension.</li><li>Name them according to style: Inset.png or Header.png.</li></ol><p>Xcode automatically picks these images for display.</p><h4>Info.plist Configuration</h4><p>Ensure your Top Shelf extension’s Info.plist contains:</p><pre>&lt;key&gt;NSExtensionPointIdentifier&lt;/key&gt;<br>&lt;string&gt;com.apple.tv-top-shelf-provider&lt;/string&gt;<br>&lt;key&gt;NSExtensionPrincipalClass&lt;/key&gt;<br>&lt;string&gt;$(PRODUCT_MODULE_NAME).TopShelfProvider&lt;/string&gt;<br>&lt;key&gt;TVTopShelfContentStyle&lt;/key&gt;<br>&lt;string&gt;Inset&lt;/string&gt; &lt;!-- or Header --&gt;</pre><p>This tells tvOS how to handle your extension and which style to use.</p><h4>Testing Your Top Shelf</h4><ol><li>Build and run your Top Shelf extension.</li><li>On Apple TV, focus on your app icon on the Home screen.</li><li>The Top Shelf content should appear dynamically.</li></ol><p><strong>Tip:</strong> Restart Apple TV if updates don’t appear immediately.</p><h4>Best Practices</h4><ul><li>Update Top Shelf content periodically rather than on every launch.</li><li>Optimize images for Apple TV resolution.</li><li>Use remote images for dynamic content to enable caching.</li><li>Test both <strong>Inset</strong> and <strong>Header</strong> styles for the best user experience.</li></ul><p>Top Shelf integration is a subtle but powerful way to increase engagement with your tvOS app. By displaying featured content even before users open the app, you can improve discoverability and retention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98e40d2cc01e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulator vs Apple TV: Why Your Files Only Save in Caches]]></title>
            <link>https://mohit-bhalla.medium.com/simulator-vs-apple-tv-why-your-files-only-save-in-caches-6fb8e05881dd?source=rss-b9a39631351a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fb8e05881dd</guid>
            <category><![CDATA[tvos-sandbox]]></category>
            <category><![CDATA[caches-directory]]></category>
            <category><![CDATA[apple-tv]]></category>
            <category><![CDATA[app-data-storage]]></category>
            <category><![CDATA[tvos]]></category>
            <dc:creator><![CDATA[Mohit Bhalla]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 12:56:39 GMT</pubDate>
            <atom:updated>2025-10-08T12:56:39.325Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve developed for <strong>tvOS</strong>, you may have noticed a curious quirk: your app can write files freely in the <strong>simulator</strong>, but the same operations fail or behave differently on a real <strong>Apple TV</strong> device. This isn’t a bug — it’s intentional and rooted in how tvOS manages app security.</p><h3>Simulator vs. Real Device: The Key Difference</h3><p>The <strong>tvOS Simulator</strong> runs on macOS, so apps inherit the Mac’s file system permissions. This allows your app to read and write files almost anywhere within the simulator environment.</p><p>On a real <strong>Apple TV</strong>, the environment is much stricter:</p><ul><li>Apps are <strong>fully sandboxed</strong> for security.</li><li>They are isolated from the system and from other apps.</li><li>Only specific directories within the app container are writable.</li></ul><p>This explains why code that works in the simulator may fail on an actual device.</p><h3>Writable Directories on Apple TV</h3><p>On tvOS, the <strong>only reliably writable directory</strong> for storing app-generated data is the <strong>Caches</strong> directory:</p><ul><li><strong>Caches</strong> — The dependable directory for storing persistent app data. It survives app launches but may be cleared by the system when storage is low.</li><li><strong>tmp</strong> — Temporary storage cleared frequently; unsuitable for persistent data.</li></ul><h3>Common Pitfalls</h3><ol><li><strong>Writing to the App Bundle</strong><br> Some developers try to store data in the app bundle. This works in the simulator but fails on real devices because the bundle is read-only.</li><li><strong>Relying on Temporary or Document Directories</strong><br> tmp is ephemeral, and Documents cannot be written to on tvOS. Depending on these locations can lead to silent failures or unexpected behavior.</li><li><strong>Testing Only in Simulator</strong><br> The simulator’s lenient behavior can be misleading. Always test file operations on a real Apple TV device to catch write restrictions early.</li></ol><h3>Conclusion</h3><p>The difference between the <strong>tvOS simulator</strong> and a <strong>real Apple TV device</strong> comes down to <strong>sandboxing and security restrictions</strong>. While the simulator allows free file writing, real devices restrict write access primarily to the Caches directory. Understanding this distinction ensures your apps behave consistently, avoids crashes, and makes your tvOS development experience smooth and predictable.</p><p>Happy Coding..</p><p>Check Other :</p><p><a href="https://mohit-bhalla.medium.com/">https://mohit-bhalla.medium.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fb8e05881dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Custom UI Components in SwiftUI]]></title>
            <link>https://mohit-bhalla.medium.com/building-custom-ui-components-in-swiftui-3d9fa1da7ae0?source=rss-b9a39631351a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d9fa1da7ae0</guid>
            <category><![CDATA[swiftui-ui-framework]]></category>
            <category><![CDATA[swiftui-ui-components]]></category>
            <category><![CDATA[swiftui-custom-card]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[custom-uibutton]]></category>
            <dc:creator><![CDATA[Mohit Bhalla]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 06:32:05 GMT</pubDate>
            <atom:updated>2025-03-28T06:32:05.135Z</atom:updated>
            <content:encoded><![CDATA[<p>SwiftUI provides a powerful and flexible way to create UI components with declarative syntax. While the built-in components are great, sometimes you need to build custom UI components to match specific design requirements. In this blog, we’ll explore how to create reusable custom UI components in SwiftUI.</p><h3>Why Build Custom UI Components?</h3><ul><li><strong>Reusability</strong>: Avoid code duplication by creating reusable components.</li><li><strong>Customization</strong>: Achieve unique designs that are not possible with default SwiftUI components.</li><li><strong>Maintainability</strong>: Keep the code clean and modular by separating UI elements into smaller, manageable components.</li></ul><h3>Creating a Custom Button</h3><p>Let’s start by building a reusable button component.</p><pre>import SwiftUI<br><br>struct CustomButton: View {<br>    var title: String<br>    var backgroundColor: Color<br>    var action: () -&gt; Void<br>    <br>    var body: some View {<br>        Button(action: action) {<br>            Text(title)<br>                .font(.headline)<br>                .foregroundColor(.white)<br>                .padding()<br>                .frame(maxWidth: .infinity)<br>                .background(backgroundColor)<br>                .cornerRadius(10)<br>                .shadow(radius: 5)<br>        }<br>        .padding(.horizontal)<br>    }<br>}<br>struct CustomButton_Previews: PreviewProvider {<br>    static var previews: some View {<br>        CustomButton(title: &quot;Click Me&quot;, backgroundColor: .blue) {<br>            print(&quot;Button tapped!&quot;)<br>        }<br>    }<br>}</pre><h3>How to Use CustomButton</h3><pre>CustomButton(title: &quot;Login&quot;, backgroundColor: .green) {<br>    print(&quot;Login button tapped&quot;)<br>}</pre><p>This button is fully reusable and customizable by changing the title, color, and action.</p><h3>Creating a Custom Card View</h3><p>A card view can be useful for displaying content in a visually appealing way. Let’s build one.</p><pre>struct CustomCardView: View {<br>    var title: String<br>    var subtitle: String<br>    var imageName: String<br>    <br>    var body: some View {<br>        VStack {<br>            Image(systemName: imageName)<br>                .resizable()<br>                .scaledToFit()<br>                .frame(width: 50, height: 50)<br>                .padding()<br>            <br>            Text(title)<br>                .font(.headline)<br>                .padding(.top, 5)<br>            <br>            Text(subtitle)<br>                .font(.subheadline)<br>                .foregroundColor(.gray)<br>                .padding(.bottom, 10)<br>        }<br>        .frame(maxWidth: .infinity)<br>        .background(Color.white)<br>        .cornerRadius(15)<br>        .shadow(radius: 5)<br>        .padding()<br>    }<br>}<br><br>struct CustomCardView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        CustomCardView(title: &quot;SwiftUI&quot;, subtitle: &quot;Building Custom UI&quot;, imageName: &quot;star.fill&quot;)<br>    }<br>}</pre><h3>Using CustomCardView</h3><pre>CustomCardView(title: &quot;Welcome&quot;, subtitle: &quot;Start exploring SwiftUI&quot;, imageName: &quot;house.fill&quot;)</pre><h3>Creating a Custom Toggle Switch</h3><p>We can also create a toggle switch with a custom design.</p><pre>struct CustomToggle: View {<br>    @Binding var isOn: Bool<br>    <br>    var body: some View {<br>        ZStack {<br>            RoundedRectangle(cornerRadius: 20)<br>                .fill(isOn ? Color.green : Color.gray)<br>                .frame(width: 50, height: 25)<br>            <br>            Circle()<br>                .fill(Color.white)<br>                .frame(width: 20, height: 20)<br>                .offset(x: isOn ? 12 : -12)<br>                .animation(.easeInOut, value: isOn)<br>        }<br>        .onTapGesture {<br>            isOn.toggle()<br>        }<br>    }<br>}<br>struct CustomToggle_Previews: PreviewProvider {<br>    static var previews: some View {<br>        CustomToggle(isOn: .constant(true))<br>    }<br>}</pre><h3>Using CustomToggle</h3><pre>@State private var toggleState = false<br>CustomToggle(isOn: $toggleState)</pre><p><strong>Conclusion:</strong></p><p>Creating custom UI components in SwiftUI helps in achieving a consistent design and better code organization. Whether it’s a button, card, or toggle switch, modular components make your app more scalable and maintainable.</p><p>Start building your own custom UI components today and take full advantage of SwiftUI’s power!</p><p>Happy Coding..</p><p>Check Other :</p><p><a href="https://mohit-bhalla.medium.com/">https://mohit-bhalla.medium.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d9fa1da7ae0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Swift Concurrency (async/await) with Real-World Examples]]></title>
            <link>https://mohit-bhalla.medium.com/understanding-swift-concurrency-async-await-with-real-world-examples-d5cbae40466e?source=rss-b9a39631351a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5cbae40466e</guid>
            <category><![CDATA[await]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[swift-async-await]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Mohit Bhalla]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 11:32:35 GMT</pubDate>
            <atom:updated>2025-03-27T11:32:35.594Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Swift Concurrency, introduced in Swift 5.5, revolutionizes how we handle asynchronous programming. By using </strong><strong>async/await, Swift makes asynchronous code easier to read, write, and maintain. In this blog, we will explore Swift Concurrency with real-world examples</strong></h4><h3>What is Swift Concurrency?</h3><p>Concurrency allows multiple tasks to run independently while ensuring optimal performance. Traditionally, we used Grand Central Dispatch (GCD) and completion handlers for managing concurrency. However, these methods often led to complex, nested, and hard-to-maintain code.</p><p>Swift Concurrency introduces:</p><ul><li>async/await: A structured way to handle asynchronous tasks.</li><li>Task: Lightweight concurrent operations.</li><li>Actor: Ensures thread safety when working with shared data.</li><li>@MainActor: Ensures UI-related updates run on the main thread.</li></ul><h3>Basics of async and await</h3><h3>Declaring an Asynchronous Function</h3><p>A function can be marked as async, indicating that it contains asynchronous work:</p><pre>func fetchData() async -&gt; String {<br>    return &quot;Data received&quot;<br>}</pre><h3>Calling an async Function</h3><p>To call an asynchronous function, use await:</p><pre>Task {<br>    let data = await fetchData()<br>    print(data)<br>}</pre><h3>Real-World Examples</h3><h3>1. Fetching Data from an API</h3><p>Fetching data from an API is a common use case for concurrency. Here’s how you can do it using async/await:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}<br><br>func fetchUserData() async throws -&gt; User {<br>    let url = URL(string: &quot;https://jsonplaceholder.typicode.com/users/1&quot;)!<br>    let (data, _) = try await URLSession.shared.data(from: url)<br>    return try JSONDecoder().decode(User.self, from: data)<br>}<br><br>Task {<br>    do {<br>        let user = try await fetchUserData()<br>        print(&quot;User: \(user.name)&quot;)<br>    } catch {<br>        print(&quot;Error: \(error)&quot;)<br>    }<br>}</pre><h4>Why Use try?</h4><p>In Swift, try is used when calling functions that can throw errors. The fetchUserData function uses try because URLSession.shared.data(from:) and JSONDecoder().decode can throw errors if the request fails or the JSON is invalid. Using try ensures we handle potential failures with a do-catch block.</p><h3>2. Running Multiple Asynchronous Tasks</h3><p>Sometimes, you may need to run multiple asynchronous tasks in parallel. You can use async let for this:</p><pre>async let firstUser = fetchUserData()<br>async let secondUser = fetchUserData()<br><br>let users = await [try firstUser, try secondUser]<br>print(users)</pre><p>This approach helps execute both tasks concurrently, improving performance.</p><h3>3. Using Actors for Thread Safety</h3><p>Actors prevent race conditions when accessing shared resources. Consider this example:</p><pre>actor BankAccount {<br>    private var balance: Int = 0<br><br>    func deposit(amount: Int) {<br>        balance += amount<br>    }<br><br>    func getBalance() -&gt; Int {<br>        return balance<br>    }<br>}<br><br>let account = BankAccount()<br>Task {<br>    await account.deposit(amount: 100)<br>    print(&quot;Balance: \(await account.getBalance())&quot;)<br>}</pre><p>Actors ensure that only one task modifies the balance at a time, preventing data inconsistencies.</p><h3>4. Ensuring UI Updates on Main Thread with @MainActor</h3><p>When updating the UI, operations should run on the main thread to avoid inconsistencies. @MainActor ensures that UI-related tasks are executed on the main thread.</p><pre>@MainActor<br>class ViewModel: ObservableObject {<br>    @Published var username: String = &quot;&quot;<br>    func loadUser() async {<br>        let user = try? await fetchUserData()<br>        username = user?.name ?? &quot;Unknown&quot;<br>    }<br>}<br>let viewModel = ViewModel()<br>Task {<br>    await viewModel.loadUser()<br>}</pre><p>Using @MainActor, we guarantee that updates to username happen on the main thread, preventing UI-related crashes.</p><h3>Conclusion</h3><p>Swift Concurrency (async/await) simplifies asynchronous programming, making it more readable and efficient. By using Task, async let, @MainActor, and actors, developers can handle concurrency with ease. Try incorporating these concepts in your Swift projects for improved performance and maintainability!</p><h3>Key Takeaways:</h3><ul><li>async/await replaces callback-based concurrency.</li><li>Task helps run async code in structured blocks.</li><li>async let enables parallel execution.</li><li>Actor ensures thread safety for shared data.</li><li>@MainActor ensures UI updates happen on the main thread.</li><li>try is necessary for handling functions that can throw errors.</li></ul><p>Start using Swift Concurrency today and write cleaner, more efficient code!</p><p>Happy Coding..</p><p>Check Other :</p><p><a href="https://mohit-bhalla.medium.com/">https://mohit-bhalla.medium.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5cbae40466e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference Between Unit Testing, Integration Testing, and System Testing in iOS Development]]></title>
            <link>https://mohit-bhalla.medium.com/difference-between-unit-testing-integration-testing-and-system-testing-in-ios-development-30134302431f?source=rss-b9a39631351a------2</link>
            <guid isPermaLink="false">https://medium.com/p/30134302431f</guid>
            <category><![CDATA[mobile-app-testing]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[ios-testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[system-testing]]></category>
            <dc:creator><![CDATA[Mohit Bhalla]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 08:34:45 GMT</pubDate>
            <atom:updated>2025-03-27T09:00:59.068Z</atom:updated>
            <content:encoded><![CDATA[<p>When developing an any application, ensuring the quality and reliability of the app is crucial. Testing plays a significant role in catching bugs early and delivering a seamless user experience. In this blog, we will discuss three key types of testing: <strong>Unit Testing, Integration Testing, and System Testing</strong> — what they are, examples, and who is responsible for each.</p><h3>1. Unit Testing</h3><h3>What is it?</h3><p>Unit testing focuses on testing individual components or functions of the application in isolation. The goal is to verify that a particular method, function, or class behaves as expected.</p><h3>Example Scenario</h3><p>Imagine you have a function in an iOS application that calculates the total price of items in a shopping cart:</p><pre>func calculateTotalPrice(items: [CartItem]) -&gt; Double {<br>    return items.reduce(0) { $0 + $1.price }<br>}</pre><p>A unit test for this function would check if it returns the correct total when given different sets of items.</p><pre>func testCalculateTotalPrice() {<br>    let items = [CartItem(price: 10.0), CartItem(price: 20.0)]<br>    let total = calculateTotalPrice(items: items)<br>    XCTAssertEqual(total, 30.0)<br>}</pre><h3>Who is Responsible?</h3><p>Unit tests are primarily written and maintained by <strong>iOS developers</strong> using XCTest or third-party frameworks like Quick/Nimble.</p><h3>2. Integration Testing</h3><h3>What is it?</h3><p>Integration testing verifies that different modules or components of the application work together correctly. It ensures that when multiple units are combined, they function properly.</p><h3>Example Scenario</h3><p>Consider a login module where the app retrieves user authentication data from a remote API.</p><ul><li><strong>Unit Test</strong> ensures that the LoginManager correctly sends a request.</li><li><strong>Integration Test</strong> ensures that LoginManager properly communicates with the network service and updates the user session after a successful login.</li></ul><pre>func testLoginIntegration() {<br>    let loginManager = LoginManager(apiService: MockAPIService())<br>    let expectation = XCTestExpectation(description: &quot;Login successful&quot;)<br>    <br>    loginManager.login(username: &quot;testuser&quot;, password: &quot;password123&quot;) { success in<br>        XCTAssertTrue(success)<br>        expectation.fulfill()<br>    }<br>    <br>    wait(for: [expectation], timeout: 5.0)<br>}</pre><h3>Who is Responsible?</h3><p>Integration tests are typically written by <strong>developers</strong> but may also involve <strong>QA engineers</strong>, especially when validating API interactions.</p><h3>3. System Testing</h3><h3>What is it?</h3><p>System testing evaluates the entire application as a whole. It ensures that all components work together as expected, considering UI, performance, and external dependencies.</p><h3>Example Scenario</h3><p>A complete end-to-end test for a food delivery app might involve:</p><ol><li>Launching the app.</li><li>Searching for a restaurant.</li><li>Placing an order.</li><li>Completing payment.</li><li>Verifying order confirmation.</li></ol><p>This type of testing is usually performed using UI automation frameworks like <strong>XCUITest</strong>:</p><pre>func testCompleteOrderFlow() {<br>    let app = XCUIApplication()<br>    app.launch()<br>    <br>    app.textFields[&quot;Search&quot;].tap()<br>    app.textFields[&quot;Search&quot;].typeText(&quot;Pizza Place&quot;)<br>    app.buttons[&quot;Order Now&quot;].tap()<br>    app.buttons[&quot;Checkout&quot;].tap()<br>    app.buttons[&quot;Confirm Payment&quot;].tap()<br>    <br>    XCTAssertTrue(app.staticTexts[&quot;Order Confirmed&quot;].exists)<br>}</pre><h3>Who is Responsible?</h3><p>System testing is usually handled by <strong>QA engineers</strong> using tools like <strong>XCUITest</strong>, <strong>Appium</strong>, or manual testing.</p><h3>Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64VWaA2uMKmmX35ecWpukQ.png" /></figure><h3>Conclusion</h3><p>Each type of testing plays a crucial role in the iOS development lifecycle. <strong>Unit tests ensure individual components work, integration tests verify interactions between them, and system tests validate the complete app experience.</strong> By implementing all three levels of testing, iOS developers and QA engineers can build reliable and bug-free applications.</p><p>Happy Coding..</p><p>Check Other :</p><p><a href="https://mohit-bhalla.medium.com/">https://mohit-bhalla.medium.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30134302431f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles in iOS Development]]></title>
            <link>https://mohit-bhalla.medium.com/solid-principles-in-ios-development-0c71216c96a7?source=rss-b9a39631351a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c71216c96a7</guid>
            <category><![CDATA[clean-architecture-ios]]></category>
            <category><![CDATA[solid-principles-ios]]></category>
            <category><![CDATA[solid-swift-examples]]></category>
            <category><![CDATA[swift-solid-design]]></category>
            <category><![CDATA[ios-app-architecture]]></category>
            <dc:creator><![CDATA[Mohit Bhalla]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 08:04:46 GMT</pubDate>
            <atom:updated>2025-03-27T09:02:05.106Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When writing clean, maintainable, and scalable iOS applications, adhering to the <strong>SOLID principles</strong> is crucial. These five design principles help developers build software that is easier to maintain, extend, and test.</p><h3>1. Single Responsibility Principle (SRP)</h3><p><em>A class should have only one reason to change.</em></p><h3>Example: Violating SRP</h3><pre>class UserManager {<br>    func saveUserToDatabase(user: User) {<br>        // Save user to database<br>    }<br>    <br>    func sendWelcomeEmail(user: User) {<br>        // Send email to user<br>    }<br>}</pre><p>Here, UserManager is handling both database operations and email sending, violating SRP.</p><h3>Fix:</h3><pre>class UserRepository {<br>    func saveUser(user: User) {<br>        // Save user to database<br>    }<br>}<br><br>class EmailService {<br>    func sendWelcomeEmail(user: User) {<br>        // Send email to user<br>    }<br>}</pre><p>Now, each class has a single responsibility, adhering to SRP.</p><h3>2. Open/Closed Principle (OCP)</h3><p><em>Software entities should be open for extension but closed for modification.</em></p><h3>Example: Violating OCP</h3><pre>class PaymentProcessor {<br>    func processPayment(method: String) {<br>        if method == &quot;creditCard&quot; {<br>            // Process credit card payment<br>        } else if method == &quot;paypal&quot; {<br>            // Process PayPal payment<br>        }<br>    }<br>}</pre><p>Every time a new payment method is added, the class must be modified.</p><h3>Fix:</h3><pre>protocol PaymentMethod {<br>    func processPayment()<br>}<br><br>class CreditCardPayment: PaymentMethod {<br>    func processPayment() {<br>        // Process credit card payment<br>    }<br>}<br><br>class PayPalPayment: PaymentMethod {<br>    func processPayment() {<br>        // Process PayPal payment<br>    }<br>}<br><br>class PaymentProcessor {<br>    func process(payment: PaymentMethod) {<br>        payment.processPayment()<br>    }<br>}</pre><p>Now, adding a new payment method doesn’t require modifying PaymentProcessor, adhering to OCP.</p><h3>3. Liskov Substitution Principle (LSP)</h3><p><em>Subtypes must be substitutable for their base types. This principle ensures that a derived class can replace its base class without changing the behavior of the system.</em></p><h3>Example: Violating LSP</h3><pre>class Bird {<br>    func fly() {<br>        print(&quot;Flying&quot;)<br>    }<br>}<br><br>class Penguin: Bird {<br>    override func fly() {<br>        fatalError(&quot;Penguins can&#39;t fly!&quot;)<br>    }<br>}</pre><p>A subclass (Penguin) is breaking the behavior of its base class, violating LSP.</p><h3>Fix:</h3><pre>protocol Flyable {<br>    func fly()<br>}<br><br>class Sparrow: Flyable {<br>    func fly() {<br>        print(&quot;Flying&quot;)<br>    }<br>}<br><br>class Penguin {}</pre><p>More detailed example:</p><pre>protocol Bird {<br>    var name: String { get }<br>}<br><br>protocol FlyingBird: Bird {<br>    func fly()<br>}<br><br>class Sparrow: FlyingBird {<br>    var name: String = &quot;Sparrow&quot;<br>    <br>    func fly() {<br>        print(&quot;\(name) is flying!&quot;)<br>    }<br>}<br><br>class Penguin: Bird {<br>    var name: String = &quot;Penguin&quot;<br>    // Penguins don&#39;t have a fly method, adhering to LSP<br>}<br><br>// Usage<br>let birds: [Bird] = [Sparrow(), Penguin()]<br><br>for bird in birds {<br>    if let flyingBird = bird as? FlyingBird {<br>        flyingBird.fly() // Now only applicable to flying birds<br>    } else {<br>        print(&quot;\(bird.name) cannot fly&quot;)<br>    }<br>}</pre><p>Now, we <strong>avoid overriding </strong><strong>fly() in subclasses where it does not make sense.</strong></p><p>By separating behaviors, we ensure LSP is maintained.</p><h3>4. Interface Segregation Principle (ISP)</h3><p><em>Clients should not be forced to depend on interfaces they do not use.</em></p><h3>Example: Violating ISP</h3><pre>protocol Worker {<br>    func work()<br>    func eat()<br>}<br><br>class Robot: Worker {<br>    func work() {<br>        print(&quot;Working&quot;)<br>    }<br>    <br>    func eat() {<br>        fatalError(&quot;Robots don&#39;t eat!&quot;)<br>    }<br>}</pre><p>Here, Robot is forced to implement eat(), which it doesn’t need.</p><h3>Fix:</h3><pre>protocol Workable {<br>    func work()<br>}<br><br>protocol Eatable {<br>    func eat()<br>}<br><br>class Human: Workable, Eatable {<br>    func work() {<br>        print(&quot;Working&quot;)<br>    }<br>    <br>    func eat() {<br>        print(&quot;Eating&quot;)<br>    }<br>}<br><br>class Robot: Workable {<br>    func work() {<br>        print(&quot;Working&quot;)<br>    }<br>}</pre><p>Now, each class only implements the relevant interfaces.</p><h3>5. Dependency Inversion Principle (DIP)</h3><p><em>High-level modules should not depend on low-level modules. Both should depend on abstractions.</em></p><h3>Example: Violating DIP</h3><pre>class MySQLDatabase {<br>    func saveData() {<br>        print(&quot;Saving data to MySQL&quot;)<br>    }<br>}<br><br>class UserService {<br>    let database = MySQLDatabase()<br>    <br>    func saveUser() {<br>        database.saveData()<br>    }<br>}</pre><p>UserService is tightly coupled to MySQLDatabase.</p><h3>Fix:</h3><pre>protocol Database {<br>    func saveData()<br>}<br><br>class MySQLDatabase: Database {<br>    func saveData() {<br>        print(&quot;Saving data to MySQL&quot;)<br>    }<br>}<br><br>class UserService {<br>    let database: Database<br>    <br>    init(database: Database) {<br>        self.database = database<br>    }<br>    <br>    func saveUser() {<br>        database.saveData()<br>    }<br>}</pre><p>Now, UserService depends on an abstraction (Database), making it flexible to work with any database.</p><h3><strong>Conclusion</strong></h3><p>Applying <strong>SOLID principles</strong> in iOS development helps in creating maintainable, scalable, and testable code. By breaking down responsibilities, following abstraction, and ensuring flexibility, your iOS applications become more robust and adaptable to changes.</p><p>Happy Coding, Keep sharing!!</p><p>Check Other :</p><p><a href="https://mohit-bhalla.medium.com/">https://mohit-bhalla.medium.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c71216c96a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FairPlay Streaming (FPS) DRM Workflow for Secure HLS Playback]]></title>
            <link>https://mohit-bhalla.medium.com/fairplay-streaming-fps-drm-workflow-for-secure-hls-playback-c61ca03bf471?source=rss-b9a39631351a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c61ca03bf471</guid>
            <category><![CDATA[fairplay-streaming]]></category>
            <category><![CDATA[hls-encryption]]></category>
            <category><![CDATA[avplayer-drm]]></category>
            <category><![CDATA[fps-drm]]></category>
            <category><![CDATA[ios-drm]]></category>
            <dc:creator><![CDATA[Mohit Bhalla]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 13:31:16 GMT</pubDate>
            <atom:updated>2025-03-27T09:02:19.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*LrVWr-ourahUkJOEgX_tvA.png" /></figure><p><strong>Overview</strong><br>FairPlay Streaming (FPS) is Apple’s DRM (Digital Rights Management) technology used to protect video content streamed over HTTP Live Streaming (HLS). It ensures secure playback by encrypting content and requiring authentication before decryption. This guide explains the complete flow for playing DRM-protected content using FPS in an iOS application with AVPlayer.</p><h4><strong>Steps to Play DRM-Protected Content Using FairPlay Streaming</strong></h4><p>1. <strong>Initialize AVPlayer</strong> with the DRM-Protected HLS URL.<br>2. <strong>Set up AVAssetResourceLoaderDelegate</strong> to handle DRM key requests.<br>3. <strong>Fetch the Application Certificate</strong> from the DRM License Server.<br>4.<strong> Generate an SPC (Server Playback Context) request.</strong><br>5.<strong> Send the SPC request</strong> to the License Server and receive a CKC (Content Key Context).<br>6. <strong>Pass the CKC to AVPlayerItem</strong> to enable decryption.<br>7. <strong>Start playing the DRM-Protected Content.</strong></p><ol><li><strong>Create an AVPlayer with DRM-Protected Content:</strong></li></ol><pre>import AVFoundation<br><br>// URL of the DRM-Protected Content (HLS Stream with .m3u8 extension)<br>let drmProtectedURL = URL(string: &quot;https://example.com/drm-protected-content.m3u8&quot;)!<br><br>// Create an AVAsset from the URL<br>let asset = AVURLAsset(url: drmProtectedURL)<br><br>// Assign a Resource Loader Delegate to Handle FPS Key Requests<br>asset.resourceLoader.setDelegate(DrmResourceLoader.shared, queue: DispatchQueue.main)<br><br>// Create an AVPlayerItem with the asset<br>let playerItem = AVPlayerItem(asset: asset)<br><br>// Create an AVPlayer<br>let player = AVPlayer(playerItem: playerItem)<br><br>// Create an AVPlayerLayer and Add it to the View<br>let playerLayer = AVPlayerLayer(player: player)<br>playerLayer.frame = yourView.bounds<br>yourView.layer.addSublayer(playerLayer)<br><br>// Start Playing<br>player.play()</pre><p><strong>2. Implement AVAssetResourceLoaderDelegate to Handle DRM Requests</strong><br>We need to handle FairPlay key requests when the player requires decryption.</p><p>DrmResourceLoader.swift</p><pre>import AVFoundation<br><br>class DrmResourceLoader: NSObject, AVAssetResourceLoaderDelegate {<br>    static let shared = DrmResourceLoader()<br><br>    func resourceLoader(_ resourceLoader: AVAssetResourceLoader, <br>                        shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -&gt; Bool {<br>        <br>        // Fetch Application Certificate<br>        fetchApplicationCertificate { certificate in<br>            guard let certificate = certificate else {<br>                loadingRequest.finishLoading(with: NSError(domain: &quot;FPS&quot;, code: -1, userInfo: nil))<br>                return<br>            }<br><br>            // Create an SPC Request<br>            guard let spcData = self.createSPCForApplicationCertificate(certificate: certificate, <br>                                                                        loadingRequest: loadingRequest) else {<br>                loadingRequest.finishLoading(with: NSError(domain: &quot;FPS&quot;, code: -2, userInfo: nil))<br>                return<br>            }<br><br>            // Send SPC to the DRM License Server &amp; Get CKC<br>            self.fetchContentKey(spcData: spcData) { ckcData in<br>                if let ckcData = ckcData {<br>                    // Provide the CKC to AVPlayer<br>                    loadingRequest.dataRequest?.respond(with: ckcData)<br>                    loadingRequest.finishLoading()<br>                } else {<br>                    loadingRequest.finishLoading(with: NSError(domain: &quot;FPS&quot;, code: -3, userInfo: nil))<br>                }<br>            }<br>        }<br>        return true<br>    }<br>}</pre><p><strong>3. Fetch the Application Certificate</strong><br>The Application Certificate is required to create an SPC request.</p><pre>func fetchApplicationCertificate(completion: @escaping (Data?) -&gt; Void) {<br>    guard let certificateURL = URL(string: &quot;https://drm.example.com/getCertificate&quot;) else {<br>        print(&quot;Invalid certificate URL&quot;)<br>        completion(nil)<br>        return<br>    }<br><br>    URLSession.shared.dataTask(with: certificateURL) { data, response, error in<br>        if let data = data, error == nil {<br>            completion(data)<br>        } else {<br>            print(&quot;Failed to fetch certificate: \(error?.localizedDescription ?? &quot;Unknown error&quot;)&quot;)<br>            completion(nil)<br>        }<br>    }.resume()<br>}</pre><p><strong>4. Generate the SPC (Server Playback Context) Request</strong><br>SPC request is generated using the certificate and asset ID.</p><pre>func createSPCForApplicationCertificate(certificate: Data, <br>                                        loadingRequest: AVAssetResourceLoadingRequest) -&gt; Data? {<br>    guard let assetIDString = loadingRequest.request.url?.host,<br>          let assetIDData = assetIDString.data(using: .utf8) else {<br>        print(&quot;Error: Invalid asset ID&quot;)<br>        return nil<br>    }<br><br>    do {<br>        // Create the SPC request<br>        let spcData = try loadingRequest.streamingContentKeyRequestData(forApp: certificate, <br>                                                                        contentIdentifier: assetIDData, <br>                                                                        options: nil)<br>        return spcData<br>    } catch {<br>        print(&quot;Error while creating SPC: \(error.localizedDescription)&quot;)<br>        return nil<br>    }<br>}</pre><p>5. <strong>Send SPC to DRM License Server &amp; Fetch CKC (Content Key Context)</strong><br>The SPC is sent to the DRM License Server, and we receive the CKC in response.</p><pre>func fetchContentKey(spcData: Data, completion: @escaping (Data?) -&gt; Void) {<br>    guard let licenseServerURL = URL(string: &quot;https://drm.example.com/getContentKey&quot;) else {<br>        print(&quot;Error: Invalid license server URL&quot;)<br>        completion(nil)<br>        return<br>    }<br><br>    var request = URLRequest(url: licenseServerURL)<br>    request.httpMethod = &quot;POST&quot;<br>    request.httpBody = spcData<br>    request.setValue(&quot;application/octet-stream&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br><br>    URLSession.shared.dataTask(with: request) { data, response, error in<br>        if let data = data, error == nil {<br>            completion(data) // CKC (Content Key Context) received successfully<br>        } else {<br>            print(&quot;Failed to fetch content key: \(error?.localizedDescription ?? &quot;Unknown error&quot;)&quot;)<br>            completion(nil)<br>        }<br>    }.resume()<br>}</pre><p><strong>Summary of the Flow</strong><br><br>1. AVPlayer requests DRM-protected content.</p><p>2. AVAssetResourceLoaderDelegate handles FPS requests</p><p>3. Application Certificate is fetched from the DRM server.</p><p>4. SPC request is generated using certificate and asset ID.</p><p>5. SPC request is sent to the License Server, and CKC is received.</p><p>6. CKC (Content Key Context) is passed to AVPlayerItem for decryption.</p><p>7. Content is decrypted and starts playing.</p><p><strong>Final Thoughts<br></strong>This implementation ensures secure playback of DRM-protected content using FairPlay Streaming (FPS) by handling the entire decryption and authorization process.</p><p><strong>Now, your AVPlayer can play DRM-protected content securely!</strong></p><p>Happy Coding, Keep sharing!!</p><p>Check Other :</p><p><a href="https://mohit-bhalla.medium.com/">https://mohit-bhalla.medium.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c61ca03bf471" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding WAL Mode in SQLite: Boosting Performance in SQL CRUD Operations for iOS]]></title>
            <link>https://mohit-bhalla.medium.com/understanding-wal-mode-in-sqlite-boosting-performance-in-sql-crud-operations-for-ios-5a8bd8be93d2?source=rss-b9a39631351a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a8bd8be93d2</guid>
            <category><![CDATA[optimize-ios-database-wal]]></category>
            <category><![CDATA[sqlite-wal-mode-in-swift]]></category>
            <category><![CDATA[sqlite-wal-mode-for-ios]]></category>
            <category><![CDATA[faster-crud-in-sqlite-wal]]></category>
            <category><![CDATA[ios-sqlite-wal-mode-guide]]></category>
            <dc:creator><![CDATA[Mohit Bhalla]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 09:20:41 GMT</pubDate>
            <atom:updated>2025-03-27T09:02:30.052Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>SQLite is a powerful database engine used in iOS applications for local data storage. However, its default <strong>rollback journal mode</strong> can cause performance issues due to frequent disk I/O operations. To optimize performance, <strong>Write-Ahead Logging (WAL) mode</strong> can be enabled, which allows concurrent reads and writes, reducing I/O overhead and improving responsiveness.</p><p>In this blog, we will explore how <strong>WAL mode benefits CRUD (Create, Read, Update, Delete) operations in iOS</strong>, and how to implement it using Swift.</p><h3>What is WAL Mode?</h3><p>By default, SQLite uses <strong>Rollback Journal Mode</strong>, where:</p><ul><li>Every transaction locks the database, preventing concurrent reads/writes.</li><li>Data is written directly to the main database file.</li><li>High I/O operations slow down performance on mobile storage (SSD).</li></ul><p>With <strong>WAL Mode</strong>, instead of writing directly to the database file, changes are logged in a separate WAL file (*.db-wal). This allows:</p><ul><li><strong>Concurrent reads and writes</strong>, improving efficiency.</li><li><strong>Faster transactions</strong>, as multiple processes can read data while writes happen in the background.</li><li><strong>Reduced I/O impact on storage devices</strong>, extending device lifespan.</li></ul><h3>Enabling WAL Mode in iOS (Swift)</h3><p>To enable WAL mode in your iOS app, modify your database initialization code.</p><h3>Enable WAL Mode When Opening the Database</h3><pre>import SQLite3<br><br>class DBHelper {<br>    var db: OpaquePointer?<br>    let dbName: String<br><br>    init?(dbName: String) {<br>        if dbName.isEmpty { return nil }<br>        self.dbName = dbName<br>        db = openDatabase()<br>        enableWALMode() // Enable WAL mode<br>    }<br><br>    private func openDatabase() -&gt; OpaquePointer? {<br>        do {<br>            let fileURL = try FileManager.default<br>                .url(/service/for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)<br>                .appendingPathComponent(dbName)<br><br>            var db: OpaquePointer? = nil<br>            if sqlite3_open(fileURL.path, &amp;db) == SQLITE_OK {<br>                print(&quot;✅ Database opened successfully.&quot;)<br>                return db<br>            } else {<br>                print(&quot;❌ Failed to open database.&quot;)<br>                return nil<br>            }<br>        } catch {<br>            print(&quot;❌ Error opening database: \(error)&quot;)<br>            return nil<br>        }<br>    }<br><br>    private func enableWALMode() {<br>        var statement: OpaquePointer?<br>        if sqlite3_prepare_v2(db, &quot;PRAGMA journal_mode=WAL;&quot;, -1, &amp;statement, nil) == SQLITE_OK {<br>            if sqlite3_step(statement) == SQLITE_ROW {<br>                print(&quot;✅ WAL mode enabled successfully.&quot;)<br>            }<br>        } else {<br>            print(&quot;❌ Failed to enable WAL mode.&quot;)<br>        }<br>        sqlite3_finalize(statement)<br>    }<br>}</pre><h3>Verify WAL Mode is Active</h3><p>To check if WAL mode is enabled, run the following query:</p><pre>var statement: OpaquePointer?<br>if sqlite3_prepare_v2(db, &quot;PRAGMA journal_mode;&quot;, -1, &amp;statement, nil) == SQLITE_OK {<br>    if sqlite3_step(statement) == SQLITE_ROW {<br>        let mode = String(cString: sqlite3_column_text(statement, 0))<br>        print(&quot;Current SQLite journal mode: \(mode)&quot;)<br>    }<br>}<br>sqlite3_finalize(statement)</pre><p>🔹 <strong>Expected Output:</strong> Current SQLite journal mode: wal</p><h3>Performance Benefits of WAL Mode for CRUD Operations</h3><h3>1. Faster INSERT (Create) Operations</h3><ul><li>Traditional mode locks the database during inserts.</li><li>WAL mode allows concurrent inserts without blocking reads.</li></ul><pre>let insertQuery = &quot;INSERT INTO Users (id, name, email) VALUES (?, ?, ?);&quot;</pre><h3>2. Optimized SELECT (Read) Operations</h3><ul><li>Reads are <strong>not blocked</strong> by ongoing writes, making queries faster.</li></ul><pre>let selectQuery = &quot;SELECT * FROM Users WHERE email = &#39;alice@example.com&#39;;&quot;</pre><h3>Efficient UPDATE Operations</h3><ul><li>Updates are logged first in the WAL file, avoiding direct writes to the main database.</li></ul><pre>let updateQuery = &quot;UPDATE Users SET name = &#39;Alice Smith&#39; WHERE id = 1;&quot;</pre><h3>Faster DELETE Operations with Checkpointing</h3><ul><li>Deletes don’t modify the database file immediately, reducing I/O impact.</li><li>Run checkpointing to merge WAL file changes efficiently.</li></ul><pre>let deleteQuery = &quot;DELETE FROM Users WHERE id = 1;&quot;<br>sqlite3_exec(db, &quot;PRAGMA wal_checkpoint(TRUNCATE);&quot;, nil, nil, nil)</pre><h3>When NOT to Use WAL Mode?</h3><ol><li>Although WAL mode improves performance, it may not be suitable in some cases:</li></ol><p>2. If your database is <strong>read-only</strong> (WAL requires write access).</p><p>3. If you <strong>frequently copy the database file while in use</strong> (WAL mode requires multiple files).</p><p>4. If your app only performs <strong>occasional writes</strong> (standard mode may be sufficient).</p><h3>How WAL Mode Handles Thread Safety</h3><ol><li><strong>Multiple Reads and Writes Can Happen Concurrently</strong> :</li></ol><ul><li>In <strong>default journal mode</strong>, a write transaction <strong>locks the entire database</strong>, blocking reads.</li><li>In <strong>WAL mode</strong>, reads can happen <strong>while a write transaction is ongoing</strong>, improving concurrency.</li><li><strong>Multiple readers and a single writer can exist simultaneously.</strong></li></ul><p><strong>2. Writes Are Still Serialized</strong> :</p><ul><li><strong>SQLite allows only one write transaction at a time</strong>, even in WAL mode.</li><li>If multiple threads try to write at the same time, they must <strong>wait for the current write transaction to complete</strong>.</li></ul><p><strong>3. Readers Never Block Writers</strong></p><ul><li>Since writes happen in the WAL file instead of the main database, readers don’t get blocked.</li><li>This is <strong>useful for high-read, low-write scenarios</strong> (e.g., analytics, caching, messaging apps).</li></ul><h3>Conclusion</h3><p>WAL mode significantly enhances <strong>SQLite performance for CRUD operations in iOS</strong> by reducing disk I/O, enabling concurrent reads/writes, and improving transaction speed. It is particularly beneficial for apps with frequent database interactions, such as messaging apps, analytics tracking, and offline storage solutions.</p><p><strong>Recommendation:</strong> If your iOS app performs frequent database reads/writes, enabling WAL mode is a must for optimal performance!</p><p>Happy Coding, Keep sharing!!</p><p>Check Other :</p><p><a href="https://mohit-bhalla.medium.com/">https://mohit-bhalla.medium.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a8bd8be93d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: components(separatedBy:) vs. split(separator:) - Which One Should You Use?]]></title>
            <link>https://mohit-bhalla.medium.com/swift-components-separatedby-vs-split-separator-which-one-should-you-use-5006abdaba1f?source=rss-b9a39631351a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5006abdaba1f</guid>
            <category><![CDATA[swift-split-string]]></category>
            <category><![CDATA[swift-string-efficiency]]></category>
            <category><![CDATA[swift-components-vs-split]]></category>
            <dc:creator><![CDATA[Mohit Bhalla]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 05:31:55 GMT</pubDate>
            <atom:updated>2025-03-27T09:02:51.328Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with strings in Swift, breaking them into smaller parts is a common task. You might have come across two different ways to achieve this: components(separatedBy:) and split(separator:). While they seem similar, they behave differently and serve different purposes. Let&#39;s dive into their differences and find out when to use each one.</p><h3>The Basics</h3><h3>components(separatedBy:)</h3><ul><li>Returns an array of String ([String]).</li><li>Preserves empty strings when encountering consecutive separators.</li><li>Suitable for splitting text by a specific delimiter.</li></ul><h4>Example:</h4><pre>let text = &quot;Swift,,is,great&quot;<br>let result = text.components(separatedBy: &quot;,&quot;)<br>print(result) // [&quot;Swift&quot;, &quot;&quot;, &quot;is&quot;, &quot;great&quot;]</pre><p>Notice that the empty string between the two commas (&quot;,,&quot;) is retained in the output.</p><h3>split(separator:)</h3><ul><li>Returns an array of Substring ([Substring]).</li><li><strong>Removes empty substrings</strong> by default.</li><li>More performant as it avoids unnecessary string copies.</li></ul><h4>Example:</h4><pre>let text = &quot;Swift,,is,great&quot;<br>let result = text.split(separator: &quot;,&quot;)<br>print(result) // [&quot;Swift&quot;, &quot;is&quot;, &quot;great&quot;]</pre><p>Here, the empty string between &quot;,,&quot; is removed. If you want to retain empty substrings, you can pass an additional parameter:</p><pre>let resultWithEmpty = text.split(separator: &quot;,&quot;, omittingEmptySubsequences: false)<br>print(resultWithEmpty) // [&quot;Swift&quot;, &quot;&quot;, &quot;is&quot;, &quot;great&quot;]</pre><h3>Key Differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWpawU2o0WX3xSmPgjSVuw.png" /></figure><p>When to Use Which?</p><p>Use components(separatedBy:) when:</p><ul><li>You <strong>need an array of </strong><strong>String</strong>, not Substring.</li><li>You <strong>want empty strings to be included</strong> in the output.</li><li>You <strong>are splitting text based on a fixed delimiter</strong> (e.g., parsing CSV data).</li></ul><p>Use split(separator:) when:</p><ul><li>You <strong>want better performance</strong> by working with Substring.</li><li>You <strong>don’t need empty strings</strong> in the output.</li><li>You <strong>want more control</strong> over empty sequences using omittingEmptySubsequences.</li></ul><h3>Final Thoughts</h3><p>Both components(separatedBy:) and split(separator:) are useful in different scenarios. If you need strict string splitting with empty values retained, go for components(separatedBy:). If performance and efficient memory handling are important, split(separator:) is the way to go.</p><p>Next time you’re splitting strings in Swift, pick the right method based on your needs!</p><p>Happy Coding, Keep sharing!!</p><p>Check Other :</p><p><a href="https://mohit-bhalla.medium.com/">https://mohit-bhalla.medium.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5006abdaba1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>