<?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 Ch. Sachin Siwal on Medium]]></title>
        <description><![CDATA[Stories by Ch. Sachin Siwal on Medium]]></description>
        <link>https://medium.com/@sachinsiwal?source=rss-960245db539e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*wAeyi0a5UGvM0KzHaQGbgQ.png</url>
            <title>Stories by Ch. Sachin Siwal on Medium</title>
            <link>https://medium.com/@sachinsiwal?source=rss-960245db539e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:05:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sachinsiwal/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[Gemma 4 Is Here — The Future of Local AI on Your Laptop (Cost, Performance, Use Cases Explained)]]></title>
            <link>https://medium.com/@sachinsiwal/gemma-4-is-here-the-future-of-local-ai-on-your-laptop-cost-performance-use-cases-explained-4aab3e8eae02?source=rss-960245db539e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aab3e8eae02</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[gemma]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Ch. Sachin Siwal]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 09:24:36 GMT</pubDate>
            <atom:updated>2026-04-05T09:25:09.250Z</atom:updated>
            <content:encoded><![CDATA[<p>A year ago, using AI meant one thing: calling an API, waiting for a response, and watching your bill grow.</p><p>With Gemma 4, you can run powerful AI models directly on your laptop. No API. No latency. No data leaving your machine.</p><p>Gemma 4 is part of that shift — and once you experience local AI, it’s hard to go back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qM20qRIBmvaUelvH.png" /></figure><h3>Why Gemma 4 Is a Big Deal</h3><p>Gemma 4 represents a fundamental change in how AI is consumed.</p><p>Instead of relying on centralized cloud services, it enables <strong>local-first AI</strong>, where models run directly on user devices. This shift reduces dependency on external providers and puts control back into the hands of developers and users.</p><p>What makes Gemma 4 especially important is its balance:</p><ul><li>Strong reasoning capabilities</li><li>Efficient enough for consumer hardware</li><li>Open and accessible</li></ul><p>This combination makes it practical, not just powerful.</p><h3>Capability and Power — Best in class</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GsjqTKHGbL378fVDhsbTsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32P-hjPmB0hu2O_iGt8G8Q.png" /></figure><h3>Cost Comparison: Gemma 4 Local vs Cloud AI</h3><h3>Cloud-Based AI Cost</h3><p>Cloud models like GPT-4 or Claude charge per token. While pricing varies, typical ranges are:</p><ul><li>$0.20 to $10+ per million tokens</li></ul><p>In real usage:</p><ul><li>Developers: $50–$300/month</li><li>Startups: $300–$1000/month</li><li>Production systems: $1000+</li></ul><p>Costs scale with usage, and the experiments become expensive.</p><h3>Local Execution Cost</h3><p>With Gemma 4:</p><ul><li>One-time hardware cost</li><li>Zero per-request cost</li></ul><p>This allows:</p><ul><li>Unlimited testing</li><li>Continuous automation</li><li>No billing pressure</li></ul><p>Over time, this is significantly cheaper.</p><h3>Cloud GPU Self-Hosting Cost</h3><p>Running your own GPU instances:</p><ul><li>T4: $0.35–$0.70/hr</li><li>A10: $0.80–$1.50/hr</li><li>A100: $2–$4/hr</li></ul><p>Monthly (24/7): $250 → $2500+</p><p>Local machines often win unless you need scale.</p><h3>Benchmark Comparison: Gemma 4 vs GPT vs Llama</h3><p>While exact scores vary by variant and benchmark, here’s a realistic positioning based on industry trends:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VvQplOM11ERO7KJRdaTMOw.png" /><figcaption>Benchmark Comparison: Gemma 4 vs GPT vs Llama</figcaption></figure><h3>Practical Insight</h3><p><strong>Gemma 4 performs very well for:</strong></p><ul><li>Coding assistance</li><li>Summarization</li><li>Structured outputs</li></ul><p><strong>GPT still leads in:</strong></p><ul><li>Deep reasoning</li><li>Complex multi-step logic</li></ul><p><strong>Llama sits in between but requires more setup.</strong></p><p>The key advantage of Gemma 4 is <strong>efficiency + usability</strong>, not raw dominance.</p><h3>Best Laptop Configuration for Running Gemma 4</h3><h3>Minimum Setup</h3><ul><li>CPU: 6-core</li><li>RAM: 16 GB</li></ul><p>Good for experimentation, but slower.</p><h3>Recommended Setup (Sweet Spot)</h3><ul><li>CPU: 8-core+</li><li>RAM: 32 GB</li><li>GPU: RTX 3060 / 4060</li></ul><p>Best balance of performance and cost.</p><h3>High-End Setup</h3><ul><li>GPU: RTX 4090</li><li>RAM: 64 GB+</li></ul><p>Near real-time AI workflows.</p><h3>MacBooks</h3><p>Apple Silicon (M2/M3/M4):</p><ul><li>16 GB minimum</li><li>32 GB ideal</li></ul><p>Great for productivity and development use cases.</p><h3>What Can You Do With Gemma 4 Locally?</h3><p>This is where things get interesting.</p><p>Local AI isn’t just cheaper — it enables workflows that cloud AI makes impractical.</p><h3>For Developers: Your Private AI Copilot</h3><p>You’re debugging a production issue. No internet dependency. No API latency. Just paste the error — and get an answer instantly.</p><p><strong>Gemma 4 enables:</strong></p><ul><li>Code generation</li><li>Refactoring legacy systems</li><li>Debugging support</li><li>Local documentation assistant</li></ul><h3>Why This Matters</h3><ul><li>No code leaves your machine</li><li>No subscription cost</li><li>Fully customizable workflows</li></ul><p><strong>You can integrate it into:</strong></p><ul><li>VS Code</li><li>CLI tools</li><li>Internal dev pipelines</li></ul><h3>For QA Engineers: Smarter Testing, Faster Releases</h3><p>Testing often gets overlooked in AI discussions, but this is where Gemma shines.</p><h3>Use Cases</h3><ul><li>Generate detailed test cases from feature descriptions</li><li>Analyze logs and identify root causes</li><li>Create automation scripts (Selenium, Playwright)</li><li>Suggest regression coverage gaps</li></ul><h3>Real Impact</h3><ul><li>Faster test cycles</li><li>Better coverage</li><li>Reduced manual effort</li></ul><p>And it works even in restricted environments.</p><h3>For Everyday Users: AI Without Boundaries</h3><p>You don’t need to be a developer.</p><p>Gemma 4 can act as:</p><ul><li>A personal assistant</li><li>A writing tool</li><li>A learning companion</li></ul><h3>Everyday Tasks</h3><ul><li>Write emails</li><li>Summarize PDFs</li><li>Generate content</li><li>Learn new concepts</li></ul><h3>The Big Advantage</h3><p>No data sharing. No privacy concerns.</p><p>Everything stays on your device.</p><h3>Real-World Performance Expectations</h3><p>Let’s be honest.</p><p>Local AI is powerful — but not magic.</p><h3>What Works Well</h3><ul><li>Coding tasks</li><li>Content generation</li><li>Summarization</li></ul><h3>What Can Be Slower</h3><ul><li>Very large prompts</li><li>Deep reasoning chains</li></ul><p>But for 80% of real-world tasks, it performs extremely well.</p><h3>Final Thoughts</h3><p>Gemma 4 may not be the most powerful model on paper.</p><p>But it solves something more important:</p><ul><li>Practical usability</li><li>Local deployment</li><li>Cost efficiency</li></ul><p>And once you start using AI locally… It stops feeling like a tool you access. It starts feeling like something you own.</p><p>Thank you for reading. <a href="https://www.linkedin.com/in/sachin-siwal/">Follow me on LinkedIn.</a></p><p>Gemma 4, Local AI models, Run AI locally, AI on laptop, LLM on local machine, Gemma vs GPT vs Llama, Open source AI models, AI cost comparison, Offline AI assistant, AI for developers, AI for QA, AI productivity tools</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aab3e8eae02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code with Intelligence — xCode 26]]></title>
            <link>https://medium.com/@sachinsiwal/code-with-intelligence-xcode-26-9203a8ce665e?source=rss-960245db539e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9203a8ce665e</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[xcode-26]]></category>
            <category><![CDATA[ai-tools]]></category>
            <dc:creator><![CDATA[Ch. Sachin Siwal]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 14:53:18 GMT</pubDate>
            <atom:updated>2025-07-18T14:53:18.781Z</atom:updated>
            <content:encoded><![CDATA[<h3>Code with Intelligence — xCode 26</h3><h3>Step-by-Step Guide to AI-Powered Development in Xcode 26</h3><p>In WWDC 2025, Apple revolutionized the developer experience with the announcement of Xcode 26, deeply integrating artificial intelligence directly into your coding workflow. This article provides a practical, step-by-step exploration of how developers can leverage AI in Xcode 26 to enhance productivity, code quality, and collaboration.</p><h3>Step 1: Set Up Your Development Environment</h3><ul><li>Download and install Xcode 26 from the Apple Developer portal.</li><li>Ensure your macOS system meets compatibility requirements (macOS Tahoe recommended).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNM6wB6mheI8qOTX2YJPnA.png" /></figure><ul><li>Launch Xcode and create a new Swift or SwiftUI project to begin.</li></ul><h3>Step 2: Activate AI Assistant in Xcode</h3><ul><li>Navigate to <strong>Preferences → Intelligence </strong>in Xcode.</li><li>Enable the AI assistant and configure settings such as code generation level (minimal, balanced, comprehensive).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*UEnsQEEPxrtRn7h_M1JV1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOKPrIAqZ05Oxiih_UUidg.png" /></figure><ul><li>Review privacy settings and ensure compliance with your project’s security requirements.</li></ul><h3>Step 3: Use AI-Powered Code Generation</h3><ul><li>Open your Swift or SwiftUI file.</li><li>Type a comment describing your desired function or UI component, for example:</li></ul><pre>// Function to fetch user profile data from API</pre><ul><li>Press Cmd + Shift + A (the AI Assistant shortcut) and watch Xcode generate the relevant Swift code.</li></ul><h3>Step 4: Leverage AI for Automated Testing</h3><ul><li>In your test files, write brief descriptions as comments of scenarios you wish to cover:</li></ul><pre>// Test user profile API response for invalid tokens</pre><ul><li>Invoke the AI Assistant (Cmd + Shift + A) to automatically generate comprehensive test cases, including edge cases.</li><li>Xcode’s AI will intelligently suggest assertions and scenarios to ensure robust test coverage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z04TaGwuN0H2RFqT5FhMdg.png" /></figure><h3>Step 5: Generate Inline Documentation and Comments</h3><ul><li>Highlight existing functions or methods.</li><li>Invoke the AI Assistant (Cmd + Shift + A) to automatically insert descriptive documentation blocks and inline comments, clarifying purpose, parameters, and return values.</li></ul><h3>Step 6: Utilize Enhanced SwiftUI Previews</h3><ul><li>Within SwiftUI views, use live previews enhanced by AI</li><li>Hover over UI components to see AI-generated suggestions for improving layouts or performance.</li><li>Use interactive resizing and immediate layout inspections to optimize your views quickly.</li></ul><h3>Step 7: Performance Optimization with AI-Driven Instruments</h3><ul><li>Open Instruments from within Xcode 26 and select the new <strong>AI-Optimized SwiftUI Template</strong>.</li><li>Record user interactions in your app to gather real-time performance metrics.</li><li>Review AI-generated insights and recommendations to improve UI responsiveness, battery efficiency, and overall performance.</li></ul><h3>Step 8: Continuous Integration and Collaborative AI</h3><ul><li>Enable collaborative AI features in your source control settings.</li><li>During code reviews, Xcode’s AI suggests improvements, detects potential bugs, and ensures consistency with best practices across your development team.</li></ul><h3>Best Practices and Tips</h3><ul><li>Regularly review and fine-tune AI configurations to align with your evolving development needs.</li><li>Combine AI suggestions with your expertise to validate generated code effectively.</li><li>Monitor AI-generated code performance regularly to ensure efficiency and maintainability.</li></ul><h3>Conclusion</h3><p>Xcode 26 is more than a development environment — it’s your AI-powered coding partner. By following these step-by-step guidelines, you can harness the full potential of AI-enhanced coding, dramatically increasing your productivity, code quality, and collaborative workflows. Embrace the future of intelligent development today!</p><p>At <a href="https://medium.com/u/a5fb09a5c518">TechAhead | App | AI | Web | Cloud |</a> We can help you clean your code and make it robust in hours. Embrace AI!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9203a8ce665e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Optimize your iOS app perfomance using MetricKit]]></title>
            <link>https://medium.com/@sachinsiwal/how-to-optimize-your-ios-app-perfomance-using-metrickit-dff48fa464a1?source=rss-960245db539e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dff48fa464a1</guid>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Ch. Sachin Siwal]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 19:37:32 GMT</pubDate>
            <atom:updated>2024-10-27T19:37:32.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZ9d7_f6SpBrYLtXPD5KYQ.png" /><figcaption>How to Optimize your iOS app perfomance using MetricKit</figcaption></figure><h3>Introduction</h3><p>For iPhone and iPad app development, one of the main aspects is the app’s performance.</p><p><a href="https://bugfender.com/blog/ios-app-perfomance-metrickit/">Performance</a> is about your application not crashing, but also how quickly and smoothly it can carry out its functions when users interact with it. An application whose functions consume a lot of battery life, or an application that doesn’t like to wait too long until it finishes whatever it wants to do, can lead to users uninstalling the app.</p><p>That is why it is very important to check the performance of the app. A tool that can help with these checks is called MetricKit. Apple introduced MetricKit with iOS 13 in 2019 to help developers better understand the performance of their apps — and what’s cool is how MetricKit automatically collects performance metrics for your app, so you will be able to achieve a better performance and improve the user satisfaction.</p><p>That way, whatever you do with your app, you’ll receive actual data created from real-life usage. This helps provide an understanding of how your app is performing in test labs conditions, of course, but also how it’s performing when deployed to users and accessed in everyday scenarios.</p><p>MetricKit is very useful for developers because it provides an overview of every aspect of an application’s performance. This includes the battery consumption for your app, as well as the memory consumption, how long the app takes to launch, and many other things that could provide useful, detailed data for later.</p><p>That fine detail will help you improve your app further, boosting its efficiency — and, most importantly, providing a better user experience.</p><h3>Understanding of MetricKit</h3><p>Apple introduced <a href="https://bugfender.com/blog/ios-app-perfomance-metrickit/">MetricKit framework </a>with iOS 13 to provide the developers with a diagnostic tool to improve the performance and health of their apps. It gives the metrics of how an application behaves on user devices, while also providing insights that are beyond the traditional method of debugging and testing.</p><p>These are the capabilities and features of MetricKit:</p><p>i) It will automatically collect daily iOS performance metrics.</p><p>ii) Metrics include details about battery usage, CPU stats, disk usage patterns, memory usage and network perfomance.</p><p>iii) Creates detailed reports of app crashes and hangs that occur during usage, thus making it necessary for maintaining app stability.</p><p>iv) Provide the energy impact of an app, complete with data to help optimize battery usage.</p><p>v) Presets the data in histograms and percentile, with details of how an app performs in various usage conditions. MetricKit frameworks can be easily integrated with the iOS application.</p><p>MetricKit works closely with the Apple developer tools Xcode and Instruments, helping to give a clear understanding and detailed view of your app and its performance.</p><p>MetricKit is designed to follow Apple policy, so it collects data anonymously and with the users’ consent. It provides insight to developers, but never analyzes personal information. Integrating MetricKit with your app is very easy and it needs very little code changes to start collecting data.</p><h3>Getting Started with MetricKit</h3><p>Starting with iOS 13, <strong>MetricKit</strong> is available to you as a Developer. Make sure the device you are using, or the device you plan to use for testing, is compatible with iOS 13 or later, whether you are using an iPhone or iPad. The latter needs to be running iPadOS 13 or later.</p><p>There are no special hardware requirements for your device to use MetricKit. To incorporate metrics in your mobile app, you need to enable MetricKit and set it up accordingly in your Xcode project.</p><p><a href="https://bugfender.com/blog/ios-app-perfomance-metrickit/">MetricKit Flow Diagram</a>:</p><p>Follow these steps to integrate <strong>MetricKit</strong> in your project:</p><p>Add the following <strong>MetricKit</strong> in your project:</p><ol><li>First, open up your Xcode project.</li><li>Go to the project settings, select your app target, and go to the ‘General‘ tab.</li><li>In the ‘Frameworks, Libraries, and Embedded Content‘ section, click the ‘+‘ and add MetricKit.</li></ol><p>Import MetricKit in your code: if you want to use MetricKit framework, you’ll need to import the file where the function is supposed to use this functionality. Add <strong>import MetricKit</strong>.</p><pre>**import MetricKit**</pre><p>Register the Metrics Delivery: to implement the <strong>MXMetricManagerSubscriber</strong> protocol in a suitable class <strong>AppDelegate</strong>. <strong>MXMetricManager.shared singleton</strong> to subscribe for metrics delivery with <strong>MXMetricManager.shared.add(self)</strong>.</p><pre>//Add MXMetric manager&#39;s singleton object.<br>MXMetricManager.shared.add(self)</pre><p>Handling Metrics Reports: Implement the methods to handle all incoming metric payloads. Like didReceive(_ payloads: [MXMetricPayload]) of MXMetricManagerSubscriber.</p><pre>func didReceive(_ payloads: [MXMetricPayload]) {<br>    for payload in payloads {<br>        // Process the payload<br>        print(&quot;Received the metric payload: \\(payload)&quot;)<br>    }<br>}</pre><p>Integration class diagram:</p><p>All these pieces interplay with the data given by MetricKit to help the app developer understand how their app is performing during real-world use. Lastly, the installation process will guide developers through how to practically use this API in the application and how to optimize the iOS app. Central to the functionality of the application, these components of MetricKit API are listed below:</p><p>i) <strong>MXMetricManager</strong>. It is a core class, used to manage the subscription to metric reports. Consequently, it will be used to add or remove subscribers and set the delivery schedule for metrics and, most crucially, to manage how and when subscribers will get metrics. Additionally,</p><p>ii) , an <strong>MXMetricPayload</strong> represents all the performance metric data collected in a 24-hour period.</p><p>iii) <strong>MXAppRunTimeMetric:</strong> contains metrics related to the app state or app during the foreground and background state. These terms or classes will manage different types of details for precise system resource items to be an MXCPUMetric, MXMemoryMetric, MXDiskIOMetric, MXNetworkTransferMetric, etc.</p><p>Finally, <strong>MXCrashDiagnostic</strong>, <strong>MXHangDiagnostic</strong>, and <strong>MXErrorDiagnostic</strong> are the classes that provide details or more diagnostics for crashing, hanging, and errors such as JSON bugs.</p><p>MetricKit Sequence Diagram:</p><h3>Core Metrics Available in MetricKit</h3><p>Overall, MetricKit is an entire area of all possible metrics that are necessary for conducting a comprehensive audit of the performance and health of iOS applications. As you can imagine, the information you receive from it is valuable and necessary for further work. This information can be used to optimize and improve your application.</p><p><strong>Performance Metrics You Can Collect with MetricKit</strong>:</p><ul><li><strong>CPU usage</strong>. This metric measures how much CPU time your application uses. It means the developers can easily determine which computations are too big and need to be optimized.</li><li><strong>Memory usage</strong>. This section measures the application’s average and peak memory consumption. More importantly, it allows you to determine if there is a memory leak or if the app is causing excess consumption.</li><li><strong>Energy usage</strong>. Determine how your application consumes energy and how efficiently the device’s energy is spent.</li><li><strong>Disk I/O</strong>. This measure collects data and statistics of read and write operations with files and the database.</li><li><strong>Network transfer</strong>. This section measures how much data is sent and received on the network.</li><li><strong>Graphics performance</strong>. Collects measurements of rendering and frame rate.</li><li><strong>User Interaction Metrics</strong> like app launch time <strong>and a</strong>pp responsiveness**.**</li></ul><p><strong>Let’s have a Detailed Look at Performance Metrics:</strong></p><ul><li><strong>CPU Usage</strong>: High CPU usage often leads to excess battery drain and your device heating up. The MetricKit reports can help point out which functions or processes are taking too much time or consuming too much energy.</li><li><strong>Memory Usage</strong>: Keeping an eye on memory usage helps identify memory leaks and highlight places where you could free up memory storage for more efficient performance.</li><li><strong>Energy Usage</strong>: This metric will help you determine the battery usage pattern of your apps and whether there are any anomalies, such as energy and power consumption spikes. It also helps show spikes that indicate when certain functions of the app are being used.</li><li><strong>Disk I/O</strong>: Optimizing the app’s disk routine ensures app performance is not reduced by disk read/write operations when using data-consuming apps.</li><li><strong>Networking Transfer</strong>: This helps developers tinker with data payloads to make data transmission to and from servers more efficient, thus reducing cost and improving responsiveness.</li></ul><p><strong>How MetricKit Gathers and Reports the Diagnostic Data:</strong></p><p>MetricKit gathers the diagnostic data using a system-wide approach that is friendly to the privacy of the user. Here’s how:</p><ul><li><strong>Data collection</strong>: MetricKit collects this data passively, i.e., in the background, so it does not interrupt the app’s normal operation. The collection is done by the system automatically, so there is uniformity.</li><li><strong>Data Reporting</strong>: The collected metric data is delivered to the subscribed app every 24 hours, and is then accessible by the developers through the MetricKit API.</li><li><strong>Reports</strong>: These diagnostic reports include detailed accounts of crashes, hangs, and errors occurred during app usage. The data compiled by these reports can help an app developer discover the cause of an issue.</li></ul><h3>Code Examples:</h3><p><strong>MXMetricPayload response handling:</strong></p><pre>func didReceive(_ payloads: [MXMetricPayload]) {<br>    for payload in payloads {<br>        // CPU Metrics data<br>        if let cpuMetrics = payload.cpuMetrics {<br>            print(&quot;CPU time: \\(cpuMetrics.cumulativeCPUTime)&quot;)<br>        }<br>        <br>        // Memory Metrics data<br>        if let memoryMetrics = payload.memoryMetrics {<br>            print(&quot;Peak memory usage: \\(memoryMetrics.peakMemoryUsage)&quot;)<br>            print(&quot;Avg memory usage: \\(memoryMetrics.averageMemoryUsage)&quot;)<br>        }<br>        <br>        // Disk I/O Metrics data<br>        if let diskMetrics = payload.diskIOMetrics {<br>            print(&quot;logical writes: \\(diskMetrics.cumulativeLogicalWrites)&quot;)<br>        }<br>        <br>        // Network Transfer Metrics data<br>        if let networkMetrics = payload.networkTransferMetrics {<br>            print(&quot;Cumulative cellular data received: \\(networkMetrics.cumulativeCellularDownload)&quot;)<br>            print(&quot;Cumulative Wi-Fi data sent: \\(networkMetrics.cumulativeWifiUpload)&quot;)<br>        }<br>        <br>        // Energy Metrics data<br>        if let energyMetrics = payload.energyMetrics {<br>            print(&quot;foreground energy consumption: \\(energyMetrics.cumulativeForegroundEnergy)&quot;)<br>            print(&quot;background energy consumption: \\(energyMetrics.cumulativeBackgroundEnergy)&quot;)<br>        }<br>        <br>        // App Launch Metrics data<br>        if let launchMetrics = payload.applicationLaunchMetrics {<br>            print(&quot;launch time: \\(launchMetrics.histogrammedTimeToFirstDraw.median)&quot;)<br>        }<br>    }<br>}</pre><p><strong>MXDiagnosticPayload response example:</strong></p><pre>func didReceive(_ payloads: [MXDiagnosticPayload]) {<br>    for payload in payloads {<br>        // Crash Diagnostics data<br>        if let crashDiagnostics = payload.crashDiagnostics {<br>            for crash in crashDiagnostics {<br>                print(&quot;Reason: of crash \\(crash.terminationReason)&quot;)<br>                print(&quot;Crash occurred: \\(crash.virtualMemorySize)&quot;)<br>            }<br>        }<br>        <br>        // Hang Diagnostics data<br>        if let hangDiagnostics = payload.hangDiagnostics {<br>            for hang in hangDiagnostics {<br>                print(&quot;Hang duration: \\(hang.hangDuration)&quot;)<br>            }<br>        }<br>        <br>        // Application Exit Diagnostics data<br>        if let exitDiagnostics = payload.applicationExitDiagnostics {<br>            for exit in exitDiagnostics {<br>                print(&quot;Exit reason: \\(exit.exitReason)&quot;)<br>                print(&quot;Exit description: \\(exit.terminationReason)&quot;)<br>            }<br>        }<br>    }<br>}</pre><h3>Handling and Interpreting the Data Collected by MetricKit</h3><p>Each payload contains highly detailed metrics regarding performance, like CPU usage, memory usage, energy impact, etc. Each of those metrics is accessed as varied properties on the payload object, such as cpuMetrics , memoryMetrics , and so on. It’s then possible to analyze these metrics to infer patterns of usage and key inferences, which may be drawn to enhance behavior and usage, such as lower energy use and reduced memory leak.</p><p>Visual representation of the data is possible with the use of tools, showing trends and deltas in these metrics as time progresses. It uses a dashboard and charting tools to examine the data in a way that is more visually apparent and effective.</p><p>It’s then possible to export the captured data and use this knowledge with additional tools. Integrated Tableau, Looker, Excel, and other analytics tools can be used to drill down into metrics and compare metrics through state, or across multiple versions.</p><h3>Best Practices for Collecting Data Efficiently</h3><p>Here is the summary of Efficient Data Collection Recommendations:</p><p><strong>Regular Monitoring</strong></p><p>Monitor these metrics on a regular basis. Use alerts or automated reports to get notifications of these metrics, either generally or whenever they cross a crucial threshold. This gives you the necessary time to inspect these metrics and give early attention to any concerns in your app’s performance.</p><p><strong>Privacy</strong></p><p>Although MetricKit abides with privacy rules, ensure that you follow them too while interacting with Measurement Data.</p><p><strong>Selective Collection</strong></p><p>Collect only metrics that are related to problems you are trying to solve. Do not gather a ton of extra data and hope you will know where to start. Having a lot of data will require a lot of cleaning before understanding, which can lead to missing some vital details.</p><p><strong>Documentation</strong></p><p>Document the metrics trends and interpretations of these measurements. Understand why some metrics are low or high, and know which metrics are expected to change and when. This will help you know what you saw when making changes, and even understand which part of your changes is causing what you see. Recorded information will be of great use in future versions of the app.</p><p>Using these rules and MetricKit will greatly help you improve your iOS apps’ performance and experience. Regular monitoring will give you a guide on what to edit to keep enhancing your app.</p><p><strong>Using MetricKit Data in the Real-World</strong></p><p><strong>Memory leak:</strong> During app testing, it was discovered that the memory usage of the app kept increasing and never reduced. This problem was fixed by investigating <strong>memoryMetrics</strong> from MetricKit, which showed the memory allocated would never be marked as free, even when it is queried. The bug was fixed, and the app’s memory usage normalized.</p><p><strong>Battery drain</strong>: during A/B testing, end-users reported that opening the app on their phones drastically reduced their battery life application at runtime. Through its dataset, a food delivery app realized that it forced the device to keep waking up every few seconds to check the network and sleep, and it was fixed. As a comparative analysis showed, the app had the network refreshed every few seconds; he metric showed the calls could be made and refueled for a day, <strong>reducing the uptime refreshment frequency equivalent to reducing battery drain by 87.5%</strong>.</p><p><strong>Launch speed</strong>: During testing, it was reported that <strong>applicationLaunchMetrics</strong> displayed the food delivery app is taking too long to launch. After investigating the launchMetrics, some CPU and IO bound tasks were discovered on the main thread. The app was fixed by making critical tasks run on the background thread.</p><h3>Integrating MetricKit with Development Workflows</h3><p>By integrating MetricKit into the daily practices of development, it is possible to achieve substantial improvement to the productivity and efficiency of iOS apps. Here are some pieces of advice on how to connect the data of MetricKit, automatize the monitoring of the performance, and use it together with additional profiling instruments included in Xcode.</p><p>Strategies for Integrating MetricKit Data into Daily Development Practices -Organizing frequent review meetings: Standard, well-scheduled meetups with your development team aimed to check the MetricKit’s reporting, discovering trends, a rise of common issues, or improvements in the fixes implementation.</p><p>Testing extension: Adding the MetricKit’s data analysis to the testing block might reduce the amount of performance related issues discovered by end-users. Pre-releasing a critical patch or update, then check the received MetricKit reports to avoid the appearance of new issues.</p><p>Performance baseline: Having the baseline to compare can help you quickly determine what part of the app or device’s performance is affected by new updates.</p><p><strong>Automating Performance Monitoring with MetricKit</strong></p><p>Establish a protocol that generates an alert based on the MetricKit data, incase a specific threshold is exceeded. One can implement a script that monitors the daily report and sends an alert if the daily memory usage exceeds a specified allowance. It is a scripted check, so that if the average standby memory is more than a predefined amount, an alert will occur. This protocol enables monitoring to be one-way and removes the daily need for manual review.</p><pre>//Function to recieve memory usage alerts<br>func didReceive(_ payloads: [MXMetricPayload]) {<br>    for payload in payloads {<br>        if payload.memoryMetrics.averageSuspendedMemory &gt; expectedMemoryUsageLimit {<br>            sendAlert(&quot;M/M usage alerts: \\(payload.memoryMetrics.averageSuspendedMemory)&quot;)<br>        }<br>    }<br>}</pre><h3>Case Studies</h3><p>MetricKit gives invaluable information that can positively impact the performance optimization of an iOS application. The following are real examples of the application of MetricKit that helped identify and eliminate performance issues, which later improved user experience and efficiency of the applications:</p><p><strong>An application which often drained social support systems users’ batteries.</strong></p><p><strong>Problem</strong>: A typical social networking application had an issue, with many users complaining about the app draining their batteries.</p><p><strong>Findings</strong>: Through the use of MetricKit, developers were able to collect and analyze battery consumption metrics. It was established that the app was continuously checking for updates, even when most users were not using the app, since they only used a video playback feature.</p><p><strong>Solution</strong>: The developers redefined a background process. This dispatched efficient polling that acquired data when necessary, and stopped checking when not required, thus enabling the app to acquire saved energy and no longer update when not required.</p><p><strong>Result</strong>: The information was already available in the trend data. According to MetricKit, the developer observed a 30% decrease in the energy consumption trend, and battery depletion cases quickly ceased to be a problem.</p><p><strong>Here is an example of feature launch time decrease in e-commerce application.</strong></p><p><strong>The problem</strong> was with an e-commerce application that showed a slow launch time. The investigation revealed that, using app data provided by MetricKit, the app startup was using resources aggressively. High resolution images are downloaded in the memory that are needed to launch the application.</p><p><strong>The solution</strong> proposed to the team was to load only the images that are used in the end from the server, and in the beginning load only low-resolution images on the feed. Due to the implementation and above change, the launch time was reduced by half. The result was that the MetricKit report confirmed suggested changes. It then behaved progressively for the next launch and no more negative feedback was given.</p><h3>To Sum up:</h3><p>In my opinion, the above examples of MetricKit metrics — such as CPU usage, memory usage, energy impact, disk I/O, network activity, and dozens of others — are important to understand the overall performance of your app.</p><p>In addition, when we have a daily report on your iOS app performance, it is possible to be constantly aware of, and correct, the issues before they become severe. The other lessons learned with MetricKit are irreplaceable. It helps developers to make adjustments and, as a result, the app consumes less battery and works more smoothly. I think these are the two most important reasons for users to be glad to use your app, as they do not care how much time you spend daily managing the app’s resources. Integration with the project was straightforward, and the daily reports helped me understand how the app works. The most critical task is to create high performance, fluent, and bug-free apps.</p><p>Use MetricKit, and you’ll be one significant step closer to being an iOS app optimization master. Apple released MetricKit framework with iOS 13, which provided a diagnostic tool to improve app performance and health. It shows the metrics of how an application behaves on the user’s devices and gives more insights than conventional frameworks can do by debugging and testing.</p><p>i) It will collect app performance metrics, daily and automatically, without any manual insights.</p><p>ii) Daily metrics will detail battery usage, CPU stats, disk usage patterns, memory usage stats, and network usage statistics.</p><p>iii) It also gives detailed reports of application crashes and hangs that have occurred while the app is being used.</p><p>iv) It will also give energy impact for apps. That data helps us optimize our battery usage.</p><p>v) It represents the data in histograms and percentile data that will tell how the application is working in different conditions of its work.</p><p>MetricKit framework can be easily added into any iOS application to monitor the mobile app performance. This works very closely with the Xcode and Instruments, so it will give a clear understanding and perspective view of your app. The integration is very easy, and it needs very little code to change to start collecting the data, so when you start any new iOS app development, plan ahead and get ready to monitor the application performance as it can make a big difference in the final app experience.</p><p>Also read about: <a href="https://bugfender.com/blog/kotlin-generics/">Kotlin Generics</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dff48fa464a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Kotlin Generics, How to use Kotlin Generics in Development]]></title>
            <link>https://towardsdev.com/understanding-kotlin-generics-how-to-use-kotlin-generics-in-development-3eda3eeb8077?source=rss-960245db539e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eda3eeb8077</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ch. Sachin Siwal]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 11:26:48 GMT</pubDate>
            <atom:updated>2024-10-09T18:17:59.826Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Kotlin Generics</h3><p><a href="https://bugfender.com/blog/kotlin-generics/">Kotlin Generics</a> are a way to use generics in Kotlin that have type parameters specified to their usage. This powerful tool defines code components so that they will work with any data type in a flexible and reusable manner — and the main advantage of Kotlin Generics is how they are statically-typed.</p><p>Kotlin Generics allow you to use three types of parameters — classes, interfaces and methods — which means it’s possible to write code to take any data type and still get compile-time type safety!</p><p>Generics help us make type-safe and reusable operations on different types of data.</p><h3>The benefits of using Generics in Kotlin</h3><p>i) Generics offer type-safety at the time of compiling the program, meaning we can catch the errors in compile-time rather than runtime.</p><p>A List in Kotlin contains objects of any type. This means mixing it up will mostly lead to runtime errors, and if our code is not written to handle such a case, it will crash the application.</p><pre>val stringLists: List&lt;String&gt; = listOf(&quot;Hola&quot;, &quot;there&quot;)</pre><p>ii) Generics assist in removing the need to do explicit type-casting, which directly contributes to much cleaner code and improved safety against ClassCastException.</p><pre>// Without use of generics <br>val listObj = listOf(1, 2, 3, 4) as List&lt;Any&gt;</pre><pre>// With the use of generics<br>val listObj: List&lt;String&gt; = listOf(&quot;Hola&quot;, &quot;there&quot;)</pre><p>iii) Generics directly contribute to the reusability of code where it’s possible to define the types and functions that can be reused anywhere in the project. You do not need to write the same code again and again for completing the same action.</p><pre>class Boxx&lt;T&gt;(var value: T) // A generic Boxx class can take any input type and can server the different purpose. </pre><pre>val intBoxx = Boxx(10) //</pre><p>iv) Generics help with writing more flexible and reusable API code. These are used in the libraries and frameworks to create broader, type-safe interfaces.</p><pre>// Creating a listOf the string items. <br>val stringLists: List&lt;String&gt; = listOf(&quot;Amma&quot;, &quot;Boby&quot;, &quot;Charls&quot;)<br>// Mapping of the items.<br>val mapItem: Map&lt;Int, String&gt; = mapOf(1 to &quot;One&quot;, 2 to &quot;Two&quot;, 3 to &quot;Three&quot;)</pre><h3>Generic Classes and Interfaces</h3><p>With Kotlin Generics, you can write the classes and interfaces with type parameters. These type parameters serve as placeholders for an actual type that will be passed to the class or interface when a copy with concrete classes is created.</p><p>Generics enable an interface to operate on objects of any type. These are really just placeholders for types; a concrete type will be substituted when the class or interface is being instantiated.</p><p><strong>a) Generic Classes</strong>: A generic class is a class that can work with any given type. Type parameter in angle brackets &lt;&gt; and used within the class, as shown.</p><pre>class Box&lt;T&gt;(var value: T)</pre><pre>fun main() {<br>    val intBox = Box(10)<br>    val stringBox = Box(&quot;Hello&quot;)</pre><pre>    println(intBox.value)  // Outputs: 10<br>    println(stringBox.value)  // Outputs: Hello<br>}</pre><p><strong>b) Generic Interfaces</strong>: Generic interfaces also have some similarity to a generic method or a generic function, wherein they mandate a better type of parameter for the generic Interface, and can be implemented with specific types by class.</p><pre>interface Repository&lt;T&gt; {<br>    fun getById(id: Int): T<br>    fun getAll(): List&lt;T&gt;<br>}</pre><pre>class UserRepository : Repository&lt;User&gt; {<br>    override fun getById(id: Int): User {<br>        // Implementation here<br>    }</pre><pre>    override fun getAll(): List&lt;User&gt; {<br>        // Implementation here<br>    }<br>}</pre><h3>Generic Methods</h3><p>Generic methods allow you to define the methods with their own type parameters. These generic type parameters can be used within the method to ensure the type safety.</p><pre>fun &lt;T&gt; printArray(array: Array&lt;T&gt;) {<br>    for (element in array) {<br>        println(element)<br>    }<br>}</pre><pre>fun main() {<br>    val intArray = arrayOf(1, 2, 3, 4, 5)<br>    val stringArray = arrayOf(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;)</pre><pre>    printArray(intArray)  // Outputs: 1 2 3 4 5<br>    printArray(stringArray)  // Outputs: one two three<br>}</pre><h3>Bounded Type Parameters</h3><p>Bounded type parameters allow you to restrict the generic types that can be used as type arguments. This can be helpful when we enforce some capabilities or behaviors on the types used with generics.</p><p><strong>a) Upper Bounds</strong>: We can also specify the upper bound for these type parameters, using the extends keyword (in Java) or the : symbol (in Kotlin). This requires the type parameter to be a subtype of that specific class.</p><pre>fun &lt;T : Number&gt; add(a: T, b: T): Double {<br>    return a.toDouble() + b.toDouble()<br>}</pre><pre>fun main() {<br>    println(add(5, 10))  // Outputs: 15.0<br>    println(add(5.5, 10.1))  // Outputs: 15.6<br>    // println(add(&quot;5&quot;, &quot;10&quot;))  // Compile-time error: argument not within its bound<br>}</pre><p><strong>b) Multiple Bounds</strong>: We could also specify multiple bounds for a type parameter, requiring the type argument to be a subtype of all specified types.</p><pre>interface Printable {<br>    fun print()<br>}</pre><pre>fun &lt;T&gt; printIfPrintable(item: T) where T : Number, T : Printable {<br>    item.print()<br>}</pre><pre>class PrintableNumber(val number: Int) : Number(), Printable {<br>    override fun print() {<br>        println(number)<br>    }</pre><pre>    // Other abstract method of Number need to be implemented<br>    override fun toByte(): Byte = number.toByte()<br>    override fun toChar(): Char = number.toChar()<br>    override fun toDouble(): Double = number.toDouble()<br>    override fun toFloat(): Float = number.toFloat()<br>    override fun toInt(): Int = number<br>    override fun toLong(): Long = number.toLong()<br>    override fun toShort(): Short = number.toShort()<br>}</pre><pre>fun main() {<br>    val printableNumber = PrintableNumber(100)<br>    printIfPrintable(printableNumber)  // Outputs: 100<br>}</pre><h3>Advanced In Generics</h3><h3>Wildcards in Generics</h3><p>Generics provide a way to specify a type parameter that allows many different types of objects to be passed in. Wildcards are represented by a question mark symbol ? and may indicate unknown types.</p><p><strong>Unbounded Wildcards example:</strong></p><pre>fun printList(list: List&lt;*&gt;) {<br>    for (item in list) {<br>        println(item)<br>    }<br>}</pre><pre>// Usage<br>val intList: List&lt;Int&gt; = listOf(1, 2, 3)<br>val stringList: List&lt;String&gt; = listOf(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;)</pre><pre>printList(intList)  // Outputs: 1 2 3<br>printList(stringList)  // Outputs: A B C</pre><p><strong>Upper-bounded wildcard</strong> (? extends T) specifies a type parameter that should be a sub-type of a specific type.</p><pre>fun sumOfNumbers(list: List&lt;out Number&gt;): Double {<br>    var sum = 0.0<br>    for (number in list) {<br>        sum += number.toDouble()<br>    }<br>    return sum<br>}</pre><pre>// Usage<br>val intList: List&lt;Int&gt; = listOf(1, 2, 3)<br>val doubleList: List&lt;Double&gt; = listOf(1.1, 2.2, 3.3)</pre><pre>println(sumOfNumbers(intList))  // Outputs: 6.0<br>println(sumOfNumbers(doubleList))  // Outputs: 6.6</pre><p><strong>A lower-bounded wildcard</strong> (? super T) specifies a type parameter that should be a super-type of a specific type.</p><pre>fun addNumbers(list: MutableList&lt;in Number&gt;) {<br>    list.add(1)<br>    list.add(1.1)<br>}</pre><pre>// Usage<br>val numberList: MutableList&lt;Number&gt; = mutableListOf(1, 2, 3)<br>addNumbers(numberList)<br>println(numberList)  // Outputs: [1, 2, 3, 1, 1.1]</pre><h3>Type Inference &amp; Type Erasure</h3><p><strong>Type inference</strong> allows a compiler of type system generics to deduce the type, such as in cases where it can be determined from context what the parameterized function or class should be.</p><pre>fun &lt;T&gt; singletonList(item: T): List&lt;T&gt; {<br>    return listOf(item)<br>}</pre><pre>// Usage<br>val intList = singletonList(1)  // Compiler infers T as Int<br>val stringList = singletonList(&quot;Hello&quot;)  // Compiler infers T as String</pre><p><strong>Type erasure</strong> is the removal, by a compiler, of redundant type information at runtime, because we already have guaranteed type-safety.</p><pre>// Example of type erasure<br>class Node&lt;T&gt;(val value: T) {<br>    fun getValue(): T = value<br>}</pre><pre>fun main() {<br>    val intNode = Node(1)<br>    val stringNode = Node(&quot;Hello&quot;)</pre><pre>    println(intNode.getValue())  // Outputs: 1<br>    println(stringNode.getValue())  // Outputs: Hello<br>}</pre><h3>Best Practices for Using Generics in Android Development</h3><h3>When to Use Generics</h3><p>In Android development, generics should be used whenever you have to write a rider of reuse code that works with multiple types.</p><ul><li><strong>Kotlin Collections and Data Structures</strong>: Use generics to avoid casting while dealing with Kotlin collections like List, Set or Map and provide type safety.</li></ul><pre>val intList: List&lt;Int&gt; = listOf(1, 2, 3)<br>val stringList: List&lt;String&gt; = listOf(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;)</pre><ul><li><strong>Adapters and View Holders</strong>: Create a universal adapter for recycler view to reuse the same logic while handling different kinds of data.</li></ul><pre>class GenericAdapter&lt;T&gt;(<br>    private val items: List&lt;T&gt;,<br>    private val bindView: (item: T, view: View) -&gt; Unit<br>) : RecyclerView.Adapter&lt;GenericAdapter.GenericViewHolder&lt;T&gt;&gt;() {<br>    // Implementation<br>}</pre><ul><li><strong>Repositories and Data Access Objects (DAOs)</strong>: Use generics to implement a repository pattern, which is even applicable for a wide range of data entities.</li></ul><pre>interface BaseDao&lt;T&gt; {<br>    fun insert(entity: T)fun update(entity: T)fun delete(entity: T)fun getById(id: Int): T<br>}</pre><ul><li><strong>Utility Methods</strong>: Write these as generic functions that you can use on any type.</li></ul><pre>fun &lt;T&gt; convertToList(vararg items: T): List&lt;T&gt; {<br>    return items.toList()<br>}</pre><h3>How to Write Clean and Maintainable Generic Code</h3><ul><li>Unobtrusive Type Parameter Names: Give type parameters meaningful names. T : Type E or Element K : Key V: Value and so on... In more complicated situations, use descriptive names.</li></ul><pre>class Repository&lt;T&gt;<br>class Pair&lt;K, V&gt;</pre><ul><li>All of these are examples of type bounds — bounded types that ensure the necessary properties and methods for what we want to do with them.</li></ul><pre>fun &lt;T : Comparable&lt;T&gt;&gt; findMax(items: List&lt;T&gt;): T {<br>    return items.maxOrNull() ?: throw NoSuchElementException()<br>}</pre><ul><li>Flexibility in APIs via Wildcards: Use wildcards to make your APIs less complex. Use in and out variances to describe producer-consumer relationships instead.</li></ul><pre>fun copy(from: List&lt;out Any&gt;, to: MutableList&lt;Any&gt;) {<br>    for (item in from) {<br>        to.add(item)<br>    }<br>}</pre><ul><li>Overuse Generics: Do not use generics for something that can be done normally. Overuse of generics can complicate the code and lead to a reduced level of readability.</li><li>Documentation — Document your generic classes and methods to explain how they are supposed to be used.</li></ul><pre>/*<br>Give the full explanation of this Generic here, so anyone who works on your project later on should understand the purpose of using it.<br>*/<br>class Box&lt;T&gt;(var value: T)</pre><h3>Common Pitfalls and How to Avoid Them</h3><ul><li>Type Erasure: keep in mind that generic type parameters are erased at runtime so you cannot use them for type checks or instance creation.</li></ul><pre>fun &lt;T&gt; isInstanceOf(value: Any, clazz: Class&lt;T&gt;): Boolean {<br>    return clazz.isInstance(value)<br>}</pre><ul><li>Unchecked Casts — Be sure to use these when you know for a fact that it is type-safe, and don’t suppress the warnings!</li></ul><pre>@Suppress(&quot;UNCHECKED_CAST&quot;)<br>fun &lt;T&gt; cast(value: Any): T {<br>    return value as T<br>}</pre><ul><li>Complex Generics: Too many little corners of your generics will 8 percent-ify them, so remember to keep it simple. Keep the generics simple, flat and avoid nesting KeyValuePair if possible to avoid complexity.</li><li>Types should be consistent within a codebase: When using generics, or any type parameter, your aim is to accurately represent what the object is, and do so consistently throughout your application. Don’t use aliases for a type parameter in different places within the code.</li></ul><h3>Conclusion</h3><p>Kotlin Generics is a de facto way in which Kotlin provides flexibility, reusability, and type-safety for your code. Generics allow us to define classes, interfaces and methods with type parameters that don’t exist at runtime (it is only used in compile-time).</p><p>Generics can catch, for example, typing errors during the compilation process, making code maintenance easier, eliminating some explicit cast between types, and making it possible to write more robust and maintainable code.</p><p>Generics are critical in helping with your design of APIs and allow you to do type-checks across the board. This in turn allows you to create safer, more flexible components in your Android projects, resulting in better application performance and an improved development experience. If fully embraced, generics will take your code to a whole new level and massively improve the quality of Android apps that you build. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eda3eeb8077" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/understanding-kotlin-generics-how-to-use-kotlin-generics-in-development-3eda3eeb8077">Understanding Kotlin Generics, How to use Kotlin Generics in Development</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning using CoreML in iOS Swift — A Step by step implementation guide]]></title>
            <link>https://blog.stackademic.com/machine-learning-using-coreml-in-ios-swift-a-step-by-step-implementation-guide-e851d87d231a?source=rss-960245db539e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e851d87d231a</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ch. Sachin Siwal]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 07:52:48 GMT</pubDate>
            <atom:updated>2024-07-19T00:16:45.716Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning using CoreML in iOS Swift — A Step by step implementation guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1J264cv5HFI8--BWw1QNJw.png" /><figcaption>Machine Learning using CoreML in iOS Swift — A Step by step implementation guide</figcaption></figure><p>A sub-discipline of artificial intelligence (AI), <a href="https://bugfender.com/blog/swift-machine-learning-using-apple-core-ml/">machine learning (ML)</a> focuses on the development of algorithms to build systems capable of learning from, and making decisions based on, data. In iOS development, ML allows us to create applications that can identify patterns and make predictions, adapting a user’s experience by learning from their behaviour. It’s this capability that drives functionality such as the content recommendations, automated workflows and predictive suggestions that have become so familiar to users of modern apps from ecommerce to email.</p><p>Read about: <a href="https://bugfender.com/blog/swift-backend/"><strong><em>Swift as a Backend</em></strong></a> &amp; <a href="https://bugfender.com/blog/swift-backend-best-practices/"><strong><em>Best Practices to Use Swift For Backend</em></strong></a></p><p>This functionality has become so ubiquitous that it’s now conspicuous by its absence, and applications that do not offer tailor-made experiences driven by ML can feel hopelessly outdated. User expectations are higher than ever and to stay relevant and competitive competition it’s crucial we embrace these advanced tools and technologies.</p><p>Today we’re going to take a look at the Core ML framework in iOS SDK to understand how it is optimized for performance on Apple devices. We’ll be considering how we can leverage the dedicated hardware to execute machine learning models and demonstrating how we can use a combination of hardware and framework to execute complex computations in real-time. We’ll be covering:</p><ul><li><a href="https://bugfender.com/blog/swift-machine-learning-using-apple-core-ml/"><strong>Machine learning</strong></a><strong> model flow</strong></li><li><strong>Apple iOS SDK machine learning frameworks</strong></li><li><strong>iOS app development using Core ML</strong></li><li><strong>Advanced ML techniques and best practices</strong></li><li><strong>Real-world applications and case studies</strong></li></ul><p>Ready? Let’s dive in!</p><h3>Machine learning model flow</h3><p>The machine learning model flow involves several stages from initialization and data collection to training, evaluation and deployment.</p><p>Below is a basic ML workflow:</p><p>Now let’s take a look at the ML frameworks available in iOS SDK.</p><h3>Apple iOS SDK machine learning frameworks</h3><p>Apple iOS SDK has many tools, frameworks and libraries for to support developers in harnessing machine learning capabilities such as image recognition and natural language analysis to build smarter applications. These frameworks can be easily used in Swift, making them ideal for integrating machine learning into iPhone and iPad apps. Let’s check out these frameworks and what they can offer.</p><h3>Core ML framework</h3><p>Core ML framework acts as the backbone when implementing machine learning in iOS apps and can be easily integrated to use existing trained models or to train new models based on data captured.</p><p><strong>Key strengths include:</strong></p><ul><li><strong>Designed for iOS:</strong> Core ML framework is tuned for iOS, making it ideal for executing machine learning models in iOS apps.</li><li><strong>Compatibility and support:</strong> Support for popular systems and formats such as TensorFlow and PyTorch means integrating these models into Core ML tools is straightforward.</li><li><strong>Security and data protection:</strong> Provides the capability to infer models locally on the device itself, ensuring the safety and privacy of user data and robust overall security.</li></ul><p><strong>Use cases could be:</strong></p><ul><li><strong>Images:</strong> Identifying and categorizing images.</li><li><strong>Objects:</strong> Detecting and tracing objects.</li><li><strong>Natural language:</strong> Understanding natural language.</li><li><strong>Prediction:</strong> Forecasting future trends through data analytics.</li></ul><h3>Vision framework</h3><p>Apple’s Vision framework offers stable APIs to perform vision related tasks such as image analysis, object, face and text detection, as well as bar code reading.</p><p><strong>Key strengths include:</strong></p><ul><li><strong>Reduced complexity:</strong> Easy to use APIs mean there is no need to implement complex logics and algorithms.</li><li><strong>Responsiveness:</strong> Works in tandem with device hardware to accelerate task processing to real-time, increasing responsiveness and overall user experience.</li><li><strong>Compatibility:</strong> Can easily be integrated with Core ML to combine computer vision algorithms with custom machine learning models.</li></ul><p><strong>Use cases could be:</strong></p><ul><li><strong>Faces:</strong> Supports face detection.</li><li><strong>Objects:</strong> Enables object Recognition.</li><li><strong>Codes:</strong> Supports Barcode and QR code scanning in real time.</li><li><strong>Text:</strong> Helps with text detection and OCR.</li><li><strong>Images:</strong> Helps with image classifications.</li></ul><h3>Create ML</h3><p>Create ML is a great tool for training the custom machine learning models on macOS. It works without the need of a detailed programming knowledge of the model trainer.</p><p>Below is a Create ML workflow:</p><p><strong>Key strengths include:</strong></p><ul><li><strong>Ease of use:</strong> A GUI based tool that makes it easy to create and train machine learning models using labeled data to train the models.</li><li><strong>Compatibility:</strong> Can be easily integrated with Xcode, which helps to export the trained models to Core ML to be used in the iOS apps.</li><li><strong>Integration:</strong> Create ML is a quick integration tool and provides instant feedback on model performance which can be used to create the reiteration.</li></ul><p><strong>Use cases could be:</strong></p><ul><li><strong>Images:</strong> Identifying and categorizing images.</li><li><strong>Objects:</strong> Detecting and tracing objects.</li><li><strong>Natural language:</strong> Understanding natural language.</li><li><strong>Sentiment:</strong> Determining the sentiment expressed in a piece of text.</li><li><strong>Data analysis and prediction:</strong> Forecasting future trends through tabular data analysis</li></ul><h3>Natural Language framework</h3><p>Apple’s Natural Language framework is made up of APIs that can perform natural language processing tasks, such as tokenization and identification of language. The Natural Language framework has a range of NLP tools for analysing and processing textual data.</p><p><strong>Key strengths include:</strong></p><ul><li><strong>Multiple language support:</strong> Can support multiple languages, detecting the language of text to support globally distributed apps.</li><li><strong>Integration with Core ML:</strong> Can be easily integrated with Core ML so NLP algorithms and custom machine learning models can be deployed together.</li></ul><p><strong>Use cases could be:</strong></p><ul><li><strong>Language Identification</strong>: Automatically identifying the language of a given text.</li><li><strong>Named Entity Recognition (NER)</strong>: Identifying and classifying proper names in text (people, organizations, locations).</li><li><strong>Sentiment Analysis</strong>: Determining the sentiment expressed in a piece of text.</li></ul><p>Fantastic! Now we’re familiar with the ML frameworks we can work with, let’s take a look at how we might integrate them when developing an iOS app.</p><h3>iOS app development using Core ML</h3><p>By integrating machine learning models we can make our apps more responsive and intuitive, delivering users a personalised experience based on their own habits and preferences. To demonstrate this we’re going to use an example of integrating image classification model in a photo editing iOS app.</p><p>Let’s get started…</p><h3>Choose the right model</h3><p>It’s essential to choose the appropriate Core ML model for the functionality we need. In our example of a photo editing app, we need to categorize images based on their nature, so we’ll select a pre-trained model such as PyTorch or TensorFlow, then convert it into the Core ML framework so we can easily integrate it.</p><h3>Convert the model to Core ML</h3><p>Now we’ve selected the right model, we’ll need to convert it to a Core ML format using the standard library conversion tools. Once converted, we’ll need to save the model to <strong>.mlmodel</strong> file format, this will keep the model architecture and parameters in the Xcode project.</p><h3>Integrate the Core ML model into our Xcode project</h3><p>Next we’ll need to integrate the model into our Xcode project, and to do this we’ll need to add the <strong>.mlmodel</strong> file to the project assets. After this file has been added, Xcode will generate Swift code to provide the Core ML API to process requests like making predictions.</p><h3>Pre-process the data</h3><p>To improve the quality of the results, input data should be pre-processed before it’s sent to be processed by the model. An example of pre-processing would be resizing images to match the input size requirements of the model, and we can write code for these pre-processing steps.</p><h3>Integrate the model into our app</h3><p>To integrate the model into our app, we need to import the Core ML framework in our ViewController class, and pass the input data (e.g. an image) so the model can return a predictive result. We can allow the user to supply an image using the device’s camera, or select an existing image from the gallery.</p><p>Here’s an example of the code we could use:</p><pre>// Example of using CoreML framework to classify the image.<br>import UIKit<br>import CoreML<br><br>class MLViewController: UIViewController {<br>    let model = BGClassifierModel()<br>    func classifyTheImage(_ image: UIImage) {<br>        if let pixelBuffers = image.pixelBuffer(width: 200, height: 200) {<br>            if let predictionResult = try? model.prediction(image: pixelBuffers) {<br>                // Handle prediction results here <br>                print(predictionResult.classLabel)<br>            }<br>        }<br>    }<br>}</pre><h3>Test the model’s performance</h3><p>Now our model is integrated into our app, it’s crucial to test it for both accuracy and speed, and this testing can be done using test data or users’ real-time generated data. Test results can then be analysed and debugging can take place.</p><h3>Optimise and iterate the model</h3><p>It’s important we keep optimizing our model based on data, errors and accuracy parameters. We’ll need to use quantization and pruning techniques to keep the model size down and improve overall capability and performance.</p><p>This process is visualized in the workflow below:</p><p>As you can see, testing and reiterating is a continuous process so we can keep making improvements.</p><h3>Deploy and monitor the model</h3><p>The final step is to deploy the ML model integrated app on the app store, so users can use it and we can monitor its performance and accuracy in production. Monitoring results will help in improving the model performance and capability over time.</p><p>Again, this process is visualized below:</p><p>Awesome! We can now build and deploy an app using a simple ML model. Let’s take a quick look at some advanced techniques and best best practices for using ML in our iOS apps.</p><h3>Advanced techniques and best practices</h3><p>Machine learning integration in iOS apps requires us to select and deploy models that are accurate, responsive and, crucially, ensure the privacy and security of user data is not compromised. There are a number of approaches to achieving this, including:</p><h3>Custom models</h3><p>Creating custom models which provide personalized predictions based on their needs, behaviour and history adds a great deal of value. For example, and app feature to identify different medical conditions like skin condition based on an image supplied could be created by training a custom model.</p><p>Here’s an example:</p><pre>// Example: Train a Custom Model with Create ML<br><br>import CreateML<br>import Foundation<br>let dataObj = try MLDataTable(contentsOf: URL(fileURLWithPath: &quot;modical_condition_dataset.csv&quot;))<br>let (trainData, testData) = dataObj.randomSplit(by: 0.8)<br>let classifiers = try MLImageClassifier(trainingData: trainData,<br>                                       validationData: testData,<br>                                       featureColumns: [&quot;images&quot;],<br>                                       targetColumn: &quot;labels&quot;)<br>let trainingMetrics = classifiers.trainingMetrics<br>try classifier.write(to: URL(fileURLWithPath: &quot;MedicalConditionClassifier.mlmodel&quot;))</pre><h3>Continuous improvement</h3><p>It’s essential to keep improving the accuracy of our models and there are a number of techniques including data augmentation, transfer learning, and ensemble techniques which can be used for continuous improvement.</p><p>As an example, for a sentiment analysis feature we could implement the transfer learning technique to fine tune the pre-trained model on any specific domain, as shown below:</p><pre>// Example: Improve and fine tune the pre trained Language Model<br><br>import CoreML<br>import NaturalLanguage<br>let sentimentalModel = try NLModel(mlModel: SentimentAnalysisModel().model)<br>sentimentalModel.update(withContentsOf: specificData)</pre><h3>Privacy and data security</h3><p>Privacy is one of, if not <em>the,</em> most important aspect of using ML models in our apps and it’s vital to ensure any sensitive data is encrypted before the model is deployed locally on the device. We also need to take steps to minimise user’s personal data exposure, for example a financial app that also has machine learning capabilities to detect any possible fraud activity. In this case, when we process any user transaction locally on the device, we also need to maintain the privacy for the transaction data for that user, which could be done like this:</p><pre>// Example: local Model Deployment for fraud detection<br><br>let fraudDetectModel = try FraudDetectionModel(configuration: .init())<br>let transactionRecord = // Any User&#39;s transaction details to process for fraud detection<br>let prediction = fraudDetectModel.predict(transactionRecord)<br>print(prediction) //print the preduction results.</pre><h3>Ethical considerations</h3><p>It’s important to use machine learning ethically and consider factors like fairness, transparency (of what, how and why data is being processed or stored), as well as accountability in the development and deployment of a machine learning model. We should implement detection of any bias detection in the outputs or predictions returned by our models. For example, a recruitment app should ensure the ML model is returning results based on the requirements and is equitable for all users.</p><p>Here’s an example:</p><pre>// Example: Bias Detection of output and Mitigation of problem<br><br>let resumeClassifiers = try ResumeScreeningModel(configuration: .init())<br>let resume = // User&#39;s resume data to process for selection<br>let prediction = resumeClassifiers.predict(resume)<br>print(prediction)<br>// It will evaluate the prediction for biases and adjust training data</pre><p>Great! Before we finish, let’s take a quick look at some familiar examples of machine learning in the real-world.</p><h3>Real-world applications and case studies</h3><p>Here are some examples of ML models in action:</p><h3>Personal assistants and chatbots</h3><p>Personal assistants such as Siri use natural language processing (NLP) and ML to understand and respond to user queries, set reminders, play music, and control smart home devices.</p><h3>Recommendation systems</h3><p>ML algorithms analyze user behavior and preferences to recommend movies, products, or music. For example, Netflix suggests movies based on user’s viewing history and Amazon recommends products based on purchase history.</p><h3>Image and speech recognition</h3><p>Applications use deep learning models to recognize objects, faces, and speech. For example Apple Face ID uses facial recognition to unlock devices.</p><h3>To sum up</h3><p>Machine learning applications are diverse and span across various industries, improving efficiency, personalization, and decision-making processes. As ML technology continues to advance, its integration into everyday applications will become even more prevalent, driving innovation and enhancing user experiences.</p><p>In this article we discussed the machine learning integration, models and major frameworks such as CoreML, Vision and CreateML which play an important role in integrating machine learning in the iOS apps.</p><p>We demonstrated how Core ML is the fundamental framework to adopt and integrate ML in iOS and how models from TensorFlow can be converted to CoreML and used directly in our apps.</p><p>We looked at the process for building ML capabilities into an application, as well as how to do this responsibly by considering data security and other ethical issues.</p><p>Hopefully you now feel confident to embrace iOS machine learning capabilities and unlock the new horizons of innovation and creativity.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e851d87d231a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/machine-learning-using-coreml-in-ios-swift-a-step-by-step-implementation-guide-e851d87d231a">Machine Learning using CoreML in iOS Swift — A Step by step implementation guide</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[Best Practices to Use Swift For Backend]]></title>
            <link>https://blog.stackademic.com/best-practices-to-use-swift-for-backend-bb7c3ba6e624?source=rss-960245db539e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb7c3ba6e624</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ch. Sachin Siwal]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 17:45:04 GMT</pubDate>
            <atom:updated>2024-07-19T00:17:01.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Wn8SsHwaRmC4YGpVi2Ldg.png" /><figcaption>Best Practices to Use Swift For Backend</figcaption></figure><p>In the last article, we gave a general introduction to <a href="https://bugfender.com/blog/swift-backend/">using Swift for backend development</a>. We discussed its advantages: its robustness, stability and, above all, its simplicity.</p><p>Now we’re going to drill a little deeper, and provide some best practices that will help you in your day-to-day work. Our work today will focus on <a href="https://vapor.codes/">Vapor</a>, an open-source web framework that provides a robust foundation for websites, APIs and Cloud projects. If you have any questions, just reach to us and we’ll do our best to help.</p><p>You might be interested in reading:</p><p><a href="https://bugfender.com/blog/swift-backend/"><strong><em>Swift as a Backend</em></strong></a> &amp; <a href="https://bugfender.com/blog/swift-backend-best-practices/"><strong><em>Best Practices to Use Swift For Backend</em></strong></a></p><p><a href="https://bugfender.com/blog/swift-machine-learning-using-apple-core-ml/"><strong><em>Machine learning in Swift iOS — A step by step guide</em></strong></a></p><h3>First, let’s explore some best practices for testing backend services</h3><p>There’s a lot of stuff we could discuss here, but here are four essential tips I personally find useful.</p><p><strong>1) Automate tools for your testing process.</strong> Continuous Integration (CI) tools like GitHub Actions, GitLab CI and Jenkins can run on every commit or pull request, catching problems early and guaranteeing good code quality.</p><p><strong>2)</strong> <strong>Aim for a good amount of tests,</strong> but understand that it’s not always feasible or necessary to reach 100% coverage. In fact, it’s best to focus only on the core critical paths and functionality that matters to your users. <strong>3) Use performance testing to point out the bottlenecks or possible issues during scalability.</strong> I’d recommend using tools like Apache JMeter, which will simulate various loads on your application.</p><p><strong>4) Look for possible vulnerabilities at all times.</strong> Static analysis or security-focused testing tools can fulfil this function in your CI/CD pipeline.</p><h3>Ok, now let’s look at a unit testing example with XCTest</h3><p>XCTest is the default unit testing framework for XCode, known for being both comprehensive and accessible. Here’s what a test with Vapor will look like.</p><pre>// VATServices.swift</pre><pre>import Vapor</pre><pre>struct VATServices {<br>    func calculateVATTax(amountV: Double, rateV: Double) -&gt; Double {<br>        return amountV * rateV / 100<br>    }<br>}</pre><pre>// VATServicesTest.swift</pre><pre>import XCTest<br>@testable import App</pre><pre>final class VATServicesTest: XCTestCase {<br>    func testCalculateVATTex() {<br>        let vatServices = VATServices()<br>        <br>        let result = vatServices.calculateVATTax(amountV: 200, rateV: 10)<br>        XCTAssertEqual(result, 20, &quot;This VAT calculation should be good&quot;)<br>    }<br>}</pre><h3>Integration testing example with Vapor</h3><p>We need to test the full process of receiving a request, processing it through our routes, and ensuring the response is as expected. This is where integration testing comes in.</p><p>Here’s an example of a test that checks a simple route and assures that it returns a 200 status code (meaning that the request was successful), with the message “Hello, world tested!”</p><p>The <strong>XCTVapor</strong> package provides the utilities to test requests and responses. Here’s an example.</p><pre>// ApplicationTest.swift</pre><pre>import XCTVapor<br>@testable import App</pre><pre>final class ApplicationTest: XCTestCase {<br>    var app: Application!<br>    <br>    override func setUp() {<br>        super.setUp()<br>        app = Application(.testing)<br>        try! configure(app)<br>    }<br>    <br>    override func tearDown() {<br>        <br>        super.tearDown()<br>        app.shutdown()<br>    }<br>    <br>    func testTheHelloWorldRoute() throws {<br>        try app.test(.GET, &quot;helloWorld&quot;, afterResponse: { res in<br>            XCTAssertEqual(res.status, .ok)<br>            XCTAssertEqual(res.body.string, &quot;Hello, world Tested!&quot;)<br>        })<br>    }<br>}</pre><h3>Debugging Swift backend code</h3><h3>Debugging with LLDB</h3><p>Ok, now let’s go a little further.</p><p>When we run a Swift backend app, we typically face issues with breakpoints and inspecting variables. Using a Low Level Debugger, we have the ability to pause the execution and test the state of the function when the program is running.</p><ol><li>Set a breakpoint in your code in the Xcode or by using <strong>breakpoint set</strong> command in LLDB.</li><li>Run the application in debug mode. From the terminal, we can start LLDB with <strong>lldb .build/debug/ExecutableName</strong>.</li><li>When execution pauses at the breakpoint, we should use LLDB commands to inspect variables or step through the code.</li></ol><p>We can use**print variableName** to print the value of the variable, and**step** or <strong>next</strong> to move through the code line by line.</p><h3>Logging for debugging</h3><p>Logging into the application can help track down issues by providing runtime info. Here’s an example of a test.</p><pre>import LoggingInfo<br>func route(_ app: Application) throws { app.get(&quot;helloRoute&quot;) { req -&gt; String in<br>    req.logger.info(&quot;Hello this route was accessed&quot;)<br>    return &quot;Hello, Bugfender world!&quot;<br>}<br>}</pre><h3>Deploying &amp; Scaling Swift Backend Services</h3><p>Now, the fun part: we can implement continuous integration continuous deployment (CI/CD) pipelines, creating scalable architectural patterns in load balancing, microservices architecture, and serverless architecture. This is key to ensuring a strong, robust backend infrastructure.</p><p>Here are some popular deployment options:</p><p><strong>Bare Metal</strong></p><p>This gives you more control of the overall infrastructure, but it involves more effort in setup and installation. In fact, you must step up Swift and prepare your app to run on a dedicated Linux server.</p><p>The server configuration setup should be started on boot, and you should deploy reverse proxy settings with Nginx or Apache servers to handle HTTP requests. <strong>Docker</strong></p><p>Containerisation with Docker will pack your app and its all dependencies into a container, assuring consistency from one environment to another. Here’s an example:</p><pre>FROM swift:latest as builder<br>WORKDIR /app<br>COPY.<br>RUN swift build -c release<br>FROM swift:slim<br>WORKDIR /app<br>COPY --from=builder /app/.build/release /app<br>CMD [&quot;./Bugfender&quot;]</pre><p><strong>Cloud Services like AWS and Azure</strong></p><p>Cloud technology provides the necessary managed services and infrastructure, allowing deployment and scaling of the application with less overhead.</p><h3>Continuous Integration/Continuous Deployment (CI/CD) Pipelines for Swift</h3><p>Now, let’s look at some CI/CD pipelines. Here’s a quick example:</p><h3>GitHub Actions Sample code:</h3><pre>name: Swift CI/CD</pre><pre>on: <br>  push:<br>    branches:<br>      - main</pre><pre>jobs:<br>  build:<br>    runs-on: ubuntu-latest</pre><pre>    steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v2</pre><pre>    - name: Set up Swift<br>      uses: fwal/setup-swift@v1</pre><pre>    - name: Build<br>      run: swift build</pre><pre>    - name: Testing<br>      run: swift test</pre><pre>    - name: Dockerize and Deploy<br>      env: <br>        DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}<br>        DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}<br>      run: |<br>        docker build -t Bugfender .<br>        echo $DOCKER_PASSWORD | docker login -u $DOCKER_USERNAME --password-stdin<br>        docker push Bugfender</pre><h3>Conclusion</h3><p>Now you should have all the knowledge you need to start using Swift for backend projects. As well as a general overview of the tools at your disposal (and the strengths and weaknesses of each one), you’ve seen plenty of code that should help you get up and running. Hopefully these articles have been accessible, engaging, and fun.</p><p>But if you require any further guidance, or have any specific questions, don’t hesitate to get in touch. We love to talk about this kind of stuff (or anything dev-related really), so let’s chat!</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb7c3ba6e624" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/best-practices-to-use-swift-for-backend-bb7c3ba6e624">Best Practices to Use Swift For Backend</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[Using Swift Vapor as a Backend Technology]]></title>
            <link>https://blog.stackademic.com/using-swift-vapor-as-a-backend-technology-1e5d832c09ac?source=rss-960245db539e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e5d832c09ac</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Ch. Sachin Siwal]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 17:39:06 GMT</pubDate>
            <atom:updated>2024-07-19T00:16:47.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Wn8SsHwaRmC4YGpVi2Ldg.png" /><figcaption>Swift as a Backend Technology</figcaption></figure><h3>Introduction to Swift as a backend technology</h3><p><a href="https://bugfender.com/blog/swift-backend-best-practices/">Swift is a powerful open source programming language created by Apple in 2014 for the iOS, iPadOS, macOS, watchOS, and tvOS, known for its modern syntax, safety features and fast performance.</a></p><p>Designed as a successor to Objective C, Swift has become a hugely popular choice for frontend and mobile app development, and it’s also shaping up to be an excellent choice for server-side development.</p><p>You might be interested in reading:</p><p><a href="https://bugfender.com/blog/swift-backend/"><strong><em>Swift as a Backend</em></strong></a> &amp; <a href="https://bugfender.com/blog/swift-backend-best-practices/"><strong><em>Best Practices to Use Swift For Backend</em></strong></a></p><p><a href="https://bugfender.com/blog/swift-machine-learning-using-apple-core-ml/"><strong><em>Machine learning in Swift iOS — A step by step guide</em></strong></a></p><h3>Swift overview and evolution for backend development</h3><p>Swift was designed to help new developers with its clean, concise syntax, while retaining benefits for power users.</p><p>The language provides modern, safe programming patterns, along with type safety, clean syntax and outstanding performance. What’s more, Swift was built as an open-source project, which has allowed the creation of frameworks such as as Vapor and Kitura. These frameworks are equipped with tools and libraries that enable us to write fully fledged server-side applications in Swift, handling HTTP requests, database integration and authentication management. This makes the language ideally suited to full stack development.</p><p>Four key reasons to use server side <a href="https://bugfender.com/blog/swift-backend-best-practices/">Swift for web development</a>:</p><p><strong>1) Performance:</strong> Swift performs strongly against C++, which is one of the fastest languages around, and it’s almost always faster than interpreted languages like Python and Ruby. Famous for its non-blocking I/O operations, Swift’s performance in CPU-bound tasks is at least the equal of its rivals, due to its compiled nature and efficient concurrency handling through the async/await syntax in Swift 5.5.</p><p><strong>2. Safety and reliability:</strong> Swift forces the handling of errors, making code not only safer but easier to read and maintain later, reducing runtime crashes and issues in the production. The compiler makes sure to warn and show all errors throughout development.</p><p><strong>3. Compatibility with Apple ecosystem:</strong> Developing a full-stack application in Swift enables us to share code, models, and business logic between frontend and backend components of an iOS, macOS, or server application. This allows for efficient and shorter software development lifecycles. And while Node.js, Ruby, and Python can serve as the backend solution for an app that has been developed in Swift, they don’t offer the compatibility advantages of using Swift at the server side.</p><p><strong>4. Vibrant community and support:</strong> As a newcomer in backend development, Swift has quickly built a vibrant and highly supportive community. It is completely open-source, accepting contributions from developers all over the world, and enables a rich ecosystem to easily build apps with libraries, frameworks, and more. The frameworks Vapor and Kitura are supported by substantial documentation, a vast number of tutorials, and thriving community support, making it very easy for developers to choose Swift for their backend projects.</p><h3>Swift server-side frameworks and tools</h3><p>We’ve already introduced Vapor and Kitura. Now, let’s explore them in more detail.</p><h3>Vapor Framework (<a href="https://vapor.codes/">https://vapor.codes/</a>)</h3><p>Vapor is a web framework that uses Swift as a server-side language, providing an expressive platform for implementing web applications and services. Vapor takes Swift’s strong typing and adds asynchronous features to provide a optimized, safe environment for server-side backend development.</p><p><strong>Features of Vapor</strong></p><p><strong>i)</strong> Asynchronous programming model using Swift’s async/await makes it easy to write non-blocking Swift code.</p><p><strong>ii)</strong> Fluent ORM is used to work with Swift databases, supporting MySQL, PostgreSQL, and SQLite.</p><p><strong>iii)</strong> Vapor has powerful routing capabilities to handle HTTP requests.</p><p><strong>iv)</strong> Vapor provides capabilities for Authentication &amp; Authorization to secure the applications.</p><p><strong>v)</strong> Vapor supports the <strong>WebSockets</strong> for real-time updates and communication.</p><p>Vapor is a great choice if high performance and scalability are among your key criteria, you intend to deploy your solutions on either Linux or macOS, and you are already handy with Swift. It’s suitable for everything from simple APIs to complex web applications and services.</p><h3>Kitura Framework (<a href="https://www.kitura.dev/">https://www.kitura.dev/</a>)</h3><p>Kitura is an <strong>IBM</strong> lightweight, modular framework for developing server-side Swift applications. It is designed in a simple but powerful way, with tools that make it easy to rapidly and easily create web apps and RESTful APIs.</p><p><strong>Features</strong>:</p><p>i) Kitura’s simplicity and speed are great for developers of all experience grades.</p><p>ii) The Model, View and Controller (MRC) pattern of Kitura is a variation of the traditional MVC pattern, made especially for server-side development.</p><p>iii) Kitura supports the Swagger developer portal for generation of API docs.</p><p>iv) Kitura supports CouchDB integration and Codable routing for handling JSON files.</p><p>v) It supports Prometheus, a powerful tool for monitoring.</p><p>Kitura is ideal for those who want simple but effective tools when developing RESTful APIs or web services, and is particularly great when integrating with IBM Cloud services or CouchDB.</p><h3>Getting Started with Swift on the server</h3><p>The following section will help you set up a working environment, create a simple REST API server, and introduce you to the most basic concepts of server-side programming in Swift.</p><h3>Installation and setup</h3><p>We need to install Swift on the development machine. Swift mainly runs on macOS, Linux, and Windows, but setting Swift up on these operating systems requires different steps. Installing Xcode from the Mac App Store includes the Swift compiler. Note that Swift can be installed through Xcode.</p><p><strong>Choose a Framework</strong></p><p>Technically it is possible to write server-side code using Swift without a framework, but both Vapor and Kitura are capable of doing things like processing HTTP requests, working with databases, and more backend tasks. In this case, we will use Vapor.</p><p><strong>Install Vapor</strong></p><p>To start your Backend using Vapor, you need to install it by running this command in your terminal (on macOS or Linux):</p><pre>brew install vapor</pre><p>This command will install Vapor on your computer.</p><h3>Building a Simple REST API Server</h3><p>Now let’s create a basic “Hello Bugfender” REST API using Vapor:</p><p><strong>Create a New Vapor Project</strong></p><p>Open your terminal and run this command:</p><pre>vapor new HelloBugfender</pre><p>This command creates a new directory called <strong>HelloBugfender</strong> with a Vapor project template.</p><p><strong>Navigate to project directory</strong></p><p>Change into your created project’s directory:</p><pre>cd HelloBugfender</pre><p><strong>Build the project</strong></p><p>Now build the project to fetch its dependencies and compile it for the first time:</p><pre>vapor build</pre><p><strong>Run the project</strong></p><p>Start the server with the run command:</p><pre>vapor run</pre><p>By default, the Vapor app runs on <strong>localhost:8080</strong>.</p><p><strong>Define a route</strong></p><p>To define a route, open the <strong>Sources/App/routes.swift</strong> file. Here, you are able to define a simple route that would return &quot;Hello, Bugfender!&quot; when accessed. Replace the contents of <strong>routes.swift</strong> with this code:</p><pre>import Vapor<br>func routes(_ app: Application) throws {<br>	app.get { req in<br>		return &quot;Hello, Bugfender!&quot;<br>	}<br>}</pre><p><strong>Test the API</strong></p><p>When the server is running, open a web browser and open <strong>http://localhost:8080/</strong>. You should see &quot;Hello, Bugfender!&quot; displayed.</p><h3>Key concepts in Swift for backend programming</h3><p><strong>Asynchronous programming</strong></p><p>The async/await-powered Swift concurrency model for server programs is able to handle I/O bound tasks well. <strong>Error handling</strong></p><p>It’s best to keep things safe and predictable on your server with Swift. Learn to work with <strong>try</strong>, <strong>catch</strong>, and <strong>throw</strong> to manage whatever server-side errors come your way.</p><p><strong>Routing</strong></p><p>Define routes to handle different HTTP requests, such as GET, POST, PUT, and DELETE.</p><p><strong>Middleware</strong></p><p>Middleware software, installed between the server and your application, can be used for logging, authentication and body parsing.</p><p><strong>Models and databases</strong></p><p>Server applications interact with databases, so you need to define the models and use ORMs such as Fluent in Vapor framework for database interactions.</p><p><strong>Serialization and deserialization</strong></p><p>Working with JSON data is one of the most common activities we carry out during backend development and integration. It doesn’t have to be complex in Swift. In fact, its <strong>Codable</strong> protocol makes things simple.</p><h3>Developing a real-world application</h3><p>The development process with Swift on the server ranges from initial planning and design of the implementation through to security integration. It helps ensure delivery of robust, secure and scalable backend apps.</p><h3>Planning and designing a Swift backend application</h3><p>You need to first define the functionalities of application and the problem the app will solve. This will help you prioritize and focus on the most fundamental and essential features first. Then you need to choose the architecture, whether it is MVC, Model-View-View-Model (MVVM) or microservices architecture. Selecting the right architecture is essential and will enable us define the scalability of the app. Once you’ve done this, it’s time to focus on the data modelling, which refers to the entity and the relationship in the data. This forms the very basis of the project, giving us a clear understanding of how data will be saved, pulled, and manipulated in the application.</p><p>Now, we get to the cool stuff: the tech stack, frameworks, databases, and other tools you are going to use. For example, if the app is developed on the server side in Swift, you might use Vapor, a database like PostgreSQL, or other libraries for things like authentication and data validation.</p><h3>Database integration: options and examples</h3><p>Mainly Swift backend devs use SQL-based databases such as PostgreSQL or MySQL, although they may also consider NoSQL databases for use with Swift.</p><p>Of the SQL databases, one of the most popular choices is PostgreSQL because of its strength, features, and easy compatibility with ORM. Fluent is Vapor’s ORM to handle the database interactions the json way.</p><p>Here are some tips that should help you along the way:</p><ul><li>Include the Fluent PostgreSQL package in your <strong>Package.swift</strong> file.</li><li>With <strong>configure.swift</strong>, establish the connection of the PostgreSQL database to your real database URL, or to specific parameters like host, username and password.</li><li>Create the Swift models conjson formed to <strong>Model</strong> and <strong>Content</strong> protocols and map them to your DB schema.</li><li>Use the Fluent migration tool to manage DB schema changes over time in the development.</li></ul><h3>Authentication and security practices</h3><p>It’s important to choose the authentication method fit for your app. For web APIs, there are several popular options, such as JWT (JSON Web Token) and OAuth methods. JWT merely provides stateless authentication, whereas OAuth is bigger and has more flexibility, so you can use it for all third-party integrations.</p><p><strong>How to implement JWT in-app</strong></p><p>We need to use the library ajsonwebtoken to issue and validate JWT tokens. Be sure to check issued tokens for every request with secure endpoint to ensure the request is authentic.</p><p><strong>OAuth integration</strong>:</p><p>If your application needs OAuth integration, it would be better to consider using some existing library or service that Swift already supports. For those apps that need to be authenticated from outside services like Google and Facebook, this works perfectly.</p><h3>Challenges and considerations</h3><p>Swift for server-side development has its strengths and tradeoffs with traditional backend technologies. These challenges and considerations are important to keep in mind, as they will certainly impact you in your day-to-day work.</p><p>Let’s look at some of them now.</p><h3>Comparison with traditional backend technologies</h3><p>Swift offers high performance. In fact, it often outperforms other dynamically typed languages like Python and Ruby for intensive computation tasks. Swift should be selected according to the needs of the app in terms of performance.</p><p>Swift has taken care to be typesafe with its modern syntax, with a focus on security achieved through features such as optional types and error handling. Other languages, such as JavaScript (with Node.js) are very lenient and dynamic, which can provide a double-edged sword: if not properly handled and implemented, they can provoke an increase in bugs.</p><p>However, other languages like Java, C#, and PHP present a huge ecosystem of libraries and frameworks for all pieces of functionality (which is no surprise, given they’ve had 30 years to develop them). Swift’s server side ecosystem, in contrast, is still growing and young.</p><p>What’s more, deployment of Swift is more complex than that of other languages, and while Swift has a very active and growing community, the server side has a smaller community than traditional backend languages.</p><h3>To sum up</h3><p>Swift has now become a big choice for server-side programming in terms of flexible performance and community dedication. In this article we have walked through several good aspects related to performance benefits, safety features, and community support. We have also described starting with Swift on the server, introduced frameworks like Vapor and Kitura, discussed the deployment and scaling of Swift backend services, and loads of other cool stuff.</p><p>We hope you enjoy using Swift in your backend development, and if you have any questions, don’t hesitate to reach out. Happy coding!</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e5d832c09ac" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/using-swift-vapor-as-a-backend-technology-1e5d832c09ac">Using Swift Vapor as a Backend Technology</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[How to implement Reactive Swift in Your iOS Apps]]></title>
            <link>https://medium.com/@sachinsiwal/how-to-implement-reactive-swift-in-your-ios-apps-760be9979a63?source=rss-960245db539e------2</link>
            <guid isPermaLink="false">https://medium.com/p/760be9979a63</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[apple-development]]></category>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Ch. Sachin Siwal]]></dc:creator>
            <pubDate>Tue, 28 May 2024 15:19:37 GMT</pubDate>
            <atom:updated>2024-05-28T15:19:37.395Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reactive Programming In Swift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBIRVqVNHeYbKfjPuAPfvQ.png" /></figure><h3>Introduction</h3><p>Our users surprise us every day. They constantly find new and exciting ways to use our apps, and create all kinds of edge cases with their behaviour. <a href="https://bugfender.com/blog/reactive-swift-rxswift/">Read More</a></p><p>As developers, it’s impossible to predict every single edge case. What we can do, however, is train our apps to react, and this is the core of Reactive programming, a development paradigm which has rapidly gained popularity for Swift programmers in recent years.</p><p>With Reactive programming, whenever any of our app’s values change, it triggers a chain reaction that filters through to all other places where this value is being used. This allows us to handle asynchronous events and operations, and makes our apps genuinely sustainable.</p><p>In this article, we’re going to give you a thorough deep-dive into Reactive Programming.</p><h3>But first, some key things to note</h3><ol><li>Reactive Programming is a subscription-based approach, where the observables emit the data and other part of the program, subscribed to the observables, reacts to the emitted events and performs accordingly.</li><li>Observers are the functions that react when any changes and events occur, and emitted events are observed to perform any task based on the new value, error or any event in the program.</li><li>Operators are used to transform, filter, and combine the observables in reactive programming, and they also allow us to create workflows by chaining the observables.</li><li>Schedulers are used to control the execution context of the observables. They are helpful in determining the thread and queue for the observable and observers to run.</li><li>Swift has several frameworks available for reactive programming, and they all have different features and syntax. Reactive Swift, RxSwift, Combine are some of the most popular frameworks.</li></ol><p><strong>RxSwift</strong> is a great reactive programming library for Swift, which is based on the <a href="https://reactivex.io/">ReactiveX</a> programming paradigm. This framework consists of reactive primitives, operators, and schedulers.</p><p><strong>Combine</strong> is a reactive programming framework which is compatible with Swift and SwiftUI, specifically designed for user interfaces.</p><h3>Why we use Reactive Programming</h3><p>Reactive programming is particularly useful when:</p><ul><li>Any piece of data changes anywhere in our project.</li><li>We want to handle asynchronous operations like updating the UI.</li><li>We want to take care of any changes or completion of key tasks, like responses received from the network request, or changing message delivery and read in real-time.</li></ul><p>In Swift, <a href="https://bugfender.com/blog/reactive-swift-rxswift/">Reactive Programming</a> is great for simplicity and readability because:</p><ol><li>It follows <strong>declarative</strong> <strong>syntax</strong>, allowing us to clearly specify and express what we want to achieve instead of specifying how to achieve it. Declarative programming provides clean, more readable code, helping to reduce the complexity of async tasks.</li><li>Reactive Swift programming has a good range of operators that help us manage complex async operations. We can chain the different operators together and create complex process pipelines.</li><li>It is based on <strong>event handling</strong>, which really helps provide a uniform approach. We can use the Observables to model various events, and Subscribers will react to these events as an when they are notified.</li><li>Reactive Swift has schedulers to maintain and manage the concurrency of task execution. We have the flexibility to specify the thread or queue on which the Observable events can be observed and executed, helping us to properly handle background tasks and UI updates along with other async tasks.</li><li>Reactive Swift has a good approach for handling execution errors. These can be sent using the Observable sequence, and Subscribers can be listed and react to errors according to defined logins and rules.</li></ol><h3>Key concepts of Reactive Programming</h3><ul><li><strong>Stream</strong> represents the flow of data, user inputs and events from one function to another emitted on any event or change. Streams are flexible and can be manipulated using the desired operators if needed.</li><li><strong>Events</strong> are the trigger occurrence in the execution of a program. They include updates in data, user interactions, or any asynchronous user activities.</li><li><strong>Schedulers</strong> determine which specific thread or queue should be observed or subscribed to. They also control the execution context of the code associated with the function. Schedulers help manage the concurrency and threading model in reactive apps.</li></ul><h3>How Reactive Swift simplifies the complex programming tasks:</h3><h3>Reactive Swift using RxSwift</h3><p><a href="https://github.com/ReactiveX/RxSwift"><strong>RxSwift</strong></a> is a reactive programming library designed to handle event-based and asynchronous tasks.</p><p>The ReactiveX framework implements this library for Swift development to facilitate the reactive programming. It is known for the powerful operators and tools it provides to compose asynchronous, event-based code and also to facilitate functional programming.</p><h3>Installation of RxSwift:</h3><p>You can use CocoaPods, Carthage, or Swift Package Manager to integrate RxSwift into your project.</p><p><strong>Using Swift Package Manager:</strong></p><p>i) In Xcode, go to File — Swift Packages — Add Package Dependency.</p><p>ii) Enter the RxSwift GitHub repository URL: <a href="https://github.com/ReactiveX/RxSwift.git."><strong>https://github.com/ReactiveX/RxSwift.git</strong>.</a></p><p>iii) Select and choose the version or branch you want to install.</p><p>iv) You can also add it to your <strong>Package.swift</strong> file:</p><pre>// Add package to your Package.swift<br>dependencies: [.package(url: &quot;&lt;https://github.com/ReactiveX/RxSwift.git&gt;&quot;, from: &quot;6.1.0&quot;)],<br>targets: [.target(name: &quot;Bugfender&quot;, dependencies: [&quot;RxSwift&quot;, &quot;RxCocoa&quot;])]</pre><p>v) After adding the dependency, run <strong>swift package update</strong> to fetch the library.</p><p><strong>Using CocoaPods:</strong></p><pre># Podfile<br>target &#39;Bugfender&#39; do<br>  use_frameworks!<br>  pod &#39;RxSwift&#39;, &#39;~&gt; 6.1&#39;<br>end</pre><p>After you add the dependency, you need to run <strong>pod install</strong> in your project directory.</p><h3>Validation using RxSwift in Swift:</h3><p>Now let’s see a step-by-step guide to implement the validations in a clear form, using RxSwift.</p><p>First, import the RxSwift Framework:</p><pre>//Import the Frameworks<br>import RxSwift<br>import RxCocoa</pre><p>Now, prepare a ViewModel class for the Form Validation:</p><pre>// Classs to validate login form<br>class LoginFormViewModel {<br>    let usernameStr = BehaviorRelay&lt;String&gt;(value: &quot;&quot;)<br>    let passwordStr = BehaviorRelay&lt;String&gt;(value: &quot;&quot;)<br>    let isFormValid: Observable&lt;Bool&gt;</pre><pre>    init() {<br>        isFormValid = Observable.combineLatest(usernameStr.asObservable(), passwordStr.asObservable())<br>            .map { usernameStr, passwordStr in<br>                return !usernameStr.isEmpty &amp;&amp; passwordStr.count &gt;= 6<br>            }<br>    }<br>}</pre><p>Using this ViewModel in Swift:</p><pre>let disposeBag = DisposeBag()<br>let viewModelLogin = LoginFormViewModel()<br>// Subscribe to changes in form validation<br>viewModelLogin.isFormValid<br>    .subscribe(onNext: { isValid in<br>        // Update the User about form validation<br>        print(&quot;Is form valid: \\(isValid)&quot;)<br>    })<br>    .disposed(by: disposeBag)</pre><p>This is an example of a simple form validation using RxSwift in Swift. The <strong>LoginFormViewModel</strong> use the <strong>BehaviorRelay</strong> to create observable properties for the username and password values, while the <strong>combineLatest</strong> operator combines the latest data values of username &amp; password and perform field validations.</p><h3>Advanced features of Reactive Swift:</h3><h3>Making Network Requests</h3><p>Reactive Swift is very good at handling asynchronous tasks like making network requests in the project. Here are the steps needed to implement such a request.</p><p>Quick note: Here we are creating an observable for a network request using RxSwift and Alamofire. The <strong>fetchData</strong> function of this service class is returning an observable that emits the received response data back to the function calling this function.</p><p>Import the RxSwift and Alamofire Frameworks:</p><pre>//Import the frameworks<br>import RxSwift<br>import RxCocoa<br>import Alamofire</pre><p>Create the Network Service Class:</p><pre>//Create the service class<br>struct NetworkServices {<br>    static func fetchData() -&gt; Observable&lt;Data&gt; {<br>        return Observable.create { observer in<br>            let request = AF.request(&quot;&lt;https://api.bugfender.com/data&gt;&quot;)<br>						//Handle the response<br>            request.responseData { response in<br>                switch response.result {<br>                case .success(let data):<br>                    observer.onNext(data)<br>                    observer.onCompleted()<br>                case .failure(let error):<br>                    observer.onError(error)<br>                }<br>            }<br>            return Disposables.create {<br>                request.cancel()<br>            }<br>        }<br>    }<br>}</pre><p>Start using the Service class in Swift Code:</p><pre>//Use the FetchData subscription in class function. <br>let disposeBag = DisposeBag()<br>//Call the api and handle the async response<br>NetworkServices.fetchData()<br>    .subscribe(onNext: { data in<br>        // Process the fetched response<br>        print(&quot;Data: \\(data)&quot;)<br>    }, onError: { error in<br>        // Handle the error if any<br>        print(&quot;Error occured: \\(error.localizedDescription)&quot;)<br>    })<br>    .disposed(by: disposeBag)</pre><p>As we can see in this Reactive Swift example, Rxswift simplifies the handling of any asynchronous event in your reactive app by using ReactiveSwift primitives. In this example, the NetworkServices.fetchData() function initiates a network request and returns an Observable. We then subscribe to this observable, where the onNext closure processes the fetched data stream, and the onError closure handles any errors that occur. This approach integrates seamlessly with Swift&#39;s Combine framework, making it an excellent choice for modern iOS development.</p><h3>State Management in a program</h3><p>Reactive Swift is very handy for managing states with its observable properties. Here RxSwift is managing and observing state changes in the program <strong>currentState</strong>, a BehaviorSubject that emits the current state, while the <strong>updateState</strong> function updates the state and UI.</p><p>To import the RxSwift Framework:</p><pre>//Import the framework<br>import RxSwift</pre><p>To create the State Manager Class:</p><pre>//Create the ManageState calss<br>class ManageState {<br>    let initialState = BehaviorSubject&lt;String&gt;(value: &quot;InitialState&quot;)</pre><pre>    func updateState(newState: String) {<br>        currentState.onNext(newState)<br>    }<br>}</pre><p>To use the StateManager in Swift code:</p><pre>//use the created State manager in your program<br>let disposeBag = DisposeBag()<br>let stateManage = ManageState()</pre><pre>stateManage.currentState<br>    .subscribe(onNext: { state in<br>        // React to the changes<br>        print(&quot;Current State of item: \\(state)&quot;)<br>    })<br>    .disposed(by: disposeBag)<br>stateManage.updateState(newState: &quot;Change the updates and UI&quot;)</pre><h3>Error Handling in RxSwift:</h3><p>Another key advantage of RxSwift is its ability to handle the errors in async tasks. Here, the <strong>errorObservable</strong> notifies and emit an error when it occurs, while the <strong>subscribe</strong> block handles the error. RxSwift has separate handlers <strong>onNext</strong>, <strong>onError</strong>, and <strong>onCompleted</strong> for different scenarios.</p><p>To import the RxSwift Framework:</p><pre>//Import the framework<br>import RxSwift</pre><p>To create the Observable with Error:</p><pre>//Create Error enum<br>enum CustomErrors: Error {<br>    case responseError<br>}</pre><pre>let errObservable = Observable&lt;String&gt;.error(CustomError.responseError)</pre><p>To use Error Handling in the Code:</p><pre>//Use the Custom error <br>let disposeBag = DisposeBag()</pre><pre>errObservable<br>    .subscribe(onError: { error in<br>        // Handle the custom error here<br>        print(&quot;Error is: \\(error.localizedDescription)&quot;)<br>    })<br>    .disposed(by: disposeBag)</pre><h3>Reactive Swift best practices</h3><p>Now we’ve gone over the top-line stuff, we’re going to round up some of the essential one-percenters that can transform your experience and maximize your productivity.</p><h3>Use dispose bags for resource management</h3><p>The <strong>DisposeBag</strong> automatically disposes of observers and subscriptions when they are no longer in use, and prevents memory leaks.</p><pre>//Dispose Bag implementation<br>let disposeBag = DisposeBag()<br>observable<br>    .subscribe(onNext: { value in<br>        // Handle the value here<br>    })<br>    .disposed(by: disposeBag)</pre><h3>Avoid strong reference cycles:</h3><p>These cycles create the memory leaks. We should use <strong>[weak self]</strong> or <strong>[unowned self]</strong> in closures to avoid any strong reference cycles when capturing the <strong>self</strong>.</p><pre>//Avoid reference cycles and memory leaks<br>observable<br>    .subscribe(onNext: { [weak self] value in<br>        // Use weak self to avoid memory leaks<br>    })<br>    .disposed(by: disposeBag)</pre><h3>Use the main scheduler and thread for UI Updates:</h3><p>Any UI update should happen on the main thread. <strong>.observeOn(MainScheduler.instance)</strong> is used to switch to the main thread.</p><pre>//Execute on main thread<br>observable<br>    .observeOn(MainScheduler.instance)<br>    .subscribe(onNext: { value in<br>        // Update the UI here<br>    })<br>    .disposed(by: disposeBag)</pre><h3>Use the throttle and debounce for performance optimization:</h3><p>We should use <strong>throttle</strong> or <strong>debounce</strong> operators to control the rate of emissions. Here’s the code.</p><pre>//Using throttle<br>textField.rx.text<br>    .throttle(.milliseconds(500), scheduler: MainScheduler.instance)<br>    .subscribe(onNext: { text in<br>        // Process the text after a 500ms delay here<br>    })<br>    .disposed(by: disposeBag)</pre><h3>Use the single subscription for shared observables</h3><p>We should prefer using <strong>.share()</strong> or <strong>.share(replay: 1)</strong> with shared observables to ensure only one subscription is made to the source observable.</p><pre>//Create shared observable<br>let sharedObservable = observable.share()</pre><h3>Testing the Reactive code</h3><p>We should use <strong>TestScheduler</strong> to handle RxSwift code and control the timing of events.</p><pre>//Using TestScheduler<br>let scheduler = TestScheduler(initialClock: 0)<br>let observable = scheduler.createHotObservable([.next(200, &quot;X&quot;), .next(250, &quot;Y&quot;)])</pre><p>Be sure to use XCTestExpectations or <strong>waitForExpectations(timeout:)</strong> to steer the asynchronous operations towards completion.</p><pre>//Using the XCTestExpectation and waitForExpectations<br>let expectations = XCTestExpectation(description: &quot;AsyncTasks&quot;)<br>observable<br>    .subscribe(onNext: { value in<br>        // Verify results<br>        expectations.fulfill()<br>    })<br>    .disposed(by: disposeBag)</pre><pre>waitForExpectations(timeout: 3, handler: nil)</pre><p>Note: we can also test different error scenarios by creating observables to emit the errors and validate the error that is being handled.</p><pre>//Error handling<br>let errObservable = Observable&lt;String&gt;.error(TestError.responseError)</pre><h3>Debugging the reactive code</h3><p>We should use <strong>.debug()</strong> in the observable to log the events and debug their sequence.</p><pre>//Using debug <br>observable<br>    .debug(&quot;Observables&quot;)<br>    .subscribe(onNext: { value in<br>        // Handle value here<br>    })<br>    .disposed(by: disposeBag)</pre><p>Now we use <strong>print</strong> to print and debug the information.</p><pre>//Use print statement<br>observable<br>    .subscribe(onNext: { value in<br>        print(&quot;Value: \\(value)&quot;)<br>    })<br>    .disposed(by: disposeBag)</pre><p>We should use the breakpoints, as well as the Low Level Debugger, to handle and fix the issues with reactive code in detail.</p><pre>// Set breakpoints<br>observable<br>    .subscribe(onNext: { value in<br>        // Set breakpoints here for debugging<br>    })<br>    .disposed(by: disposeBag)</pre><h3>To sum up</h3><p>Reactive Swift is a great approach to handle and manage the ongoing changes in a program, and respond to asynchronous tasks. It uses the powerful RxSwift framework, along with solid reactive programming principles, to create maintainable, scalable, and responsive code.</p><p>As well as discussing the essential benefits of RxSwift, we have discussed a number of fundamental concepts like observables, subscribers, operators, streams, events, and schedulers. We have also covered key everyday facets of reactive programming like network requests, state management, and error handling, while addressing best practices such as the use of disposal bags.</p><p>Remember: good debugging is essential to identify and resolve the issues in reactive code. So if you want to see how Bugfender can help, please reach out to us.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=760be9979a63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implementing iOS Universal Links in the iOS Swift App]]></title>
            <link>https://medium.com/@sachinsiwal/how-to-implementing-ios-universal-links-in-the-ios-swift-app-ec475d06e5ce?source=rss-960245db539e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec475d06e5ce</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-universal-link]]></category>
            <category><![CDATA[universal-links]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ch. Sachin Siwal]]></dc:creator>
            <pubDate>Mon, 27 May 2024 14:53:29 GMT</pubDate>
            <atom:updated>2024-07-16T08:00:03.684Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Implementing iOS Universal Links for Enhanced App-Web Navigation" src="https://cdn-images-1.medium.com/max/1024/1*shudb63LEvlgnIM1cK3yjg.png" /></figure><p><a href="https://bugfender.com/blog/ios-universal-links/">Universal Links are an iOS feature allowing seamless integration between web content and native iOS apps.</a> With iOS Universal Links we can intelligently configure a specific web URL, associating it with our iOS app so it will open directly when the URL is clicked. <a href="https://bugfender.com/blog/ios-universal-links/">Read More</a></p><p>You might be interested in reading:</p><p><a href="https://bugfender.com/blog/swift-backend/"><strong><em>Swift as a Backend</em></strong></a> &amp; <a href="https://bugfender.com/blog/swift-backend-best-practices/"><strong><em>Best Practices to Use Swift For Backend</em></strong></a></p><p><a href="https://bugfender.com/blog/swift-machine-learning-using-apple-core-ml/"><strong><em>Machine learning in Swift iOS — A step by step guide</em></strong></a></p><p>Universal Links offer multiple benefits when compared to the deep linking and custom URL scheme methods required prior to their introduction by Apple, including:</p><ul><li><strong>User experience:</strong> Seamlessly transitioning between a website and native app is much smoother and provides a greatly enhanced user experience</li><li><strong>Engagement and retention:</strong> The ability to direct users to an app without interrupting their experience brings the app’s features and capabilities into play to increase engagement and retention.</li><li><strong>Analytics and insight:</strong> Universal Links increase the opportunities for tracking user interactions with an app to gain valuable insight into behaviour.</li></ul><p>There’s no question Universal Links are a powerful tool for integrating web and app content but ensuring they work as they should requires careful configuration and that’s what we’ll be looking at in this article. Let’s get started…</p><h3>Setting up Universal Links</h3><p><a href="https://bugfender.com/blog/ios-universal-links/">We’ll begin with a walkthrough of how Universal Links work and the steps we need to follow to use them in our projects</a>. For Universal Links to work properly we’ll need to configure both the iOS app and website to support them, starting by:</p><ul><li><strong>Creating an AASA file:</strong> Step one is to create an Apple App Site Association (AASA) file. This is a JSON file which is hosted on the website server and is crucial as it declares which custom URL schemes are associated with the app.</li><li><strong>Uploading the AASA file to the website:</strong> Once the AASA file has been created, step two is to upload the file to the root of the associated website server. It’s essential the file is hosted at the root of the server so a secure connection between the associated domain and the iOS app can be maintained.</li><li><strong>Configuring associate domains:</strong> As each Apple Universal Link must correspond to a specific domain and path on the website, step three is to configure the Xcode project settings accordingly. It’s crucial this be configured correctly as, when the link is clicked, iOS will check and return an error if not.</li></ul><p>To create the AASA file, you need to upload a JSON file called apple-app-site-association (without any file extensions). The file should be accessible in https://&lt;mydomain&gt;/apple-app-site-association and be sure that the content type of the file is application/json. The file should have the following content:</p><pre>{<br>  &quot;applinks&quot;: {<br>    &quot;apps&quot;: [],<br>    &quot;details&quot;: [<br>      {<br>        &quot;appID&quot;: &quot;TEAM_ID.APP_BUNDLE_ID&quot;,<br>        &quot;paths&quot;: [ &quot;/path/to/content/*&quot;, &quot;/another/path/*&quot; ]<br>      }<br>    ]<br>  }<br>}</pre><p>In the file you will need to put <strong>TEAM_ID</strong> which is your Apple Developer ID, then the <strong>BUNDLE_ID</strong> that corresponds to you app bundle identifier and finally all the <strong>paths</strong> associated to the app (you can use wildcards in the paths). The <strong>apps</strong> field it’s a legacy field that should be present and you should use an empty array.</p><p>Great, once the above steps are complete and the app is installed, iOS will open the app directly to the specified content when the app link is clicked, without needing to open the link in Safari or prompt the user.</p><p>But what about handling Universal Linking inside the app? We’ll look at that next…</p><h3>Handling Universal Links inside the app</h3><p>Inside the app, Universal Links can be handled by implementing the app delegate specificUIApplicationDelegate method - application:continueUserActivity:restorationHandler:. iOS will call this method when the app is launched from a Universal Link and responds to the user&#39;s interaction.</p><p>Let’s demonstrate with an example:</p><pre>//AppDelegate methods to handle the universal links<br>func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -&gt; Void) -&gt; Bool {<br>    // Handle the Universal Links when app is launched<br>		print(userActivity)<br>    return true<br>}</pre><p>Once implemented, we can take control of the flow of the application when a Universal Link is clicked, customizing the behaviour and redirection based on the incoming user activity.</p><h3>Extracting data from UserActivity</h3><p>Having implemented the <strong>application:continueUserActivity:restorationHandler:</strong> method, the app is now able to extract the relevant data from the Universal Link. This includes the parameters, paths and other essential information to direct the user to the required screen or feature.</p><p>Let’s look at an example:</p><pre>//Reading the data from redirected URL<br>func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -&gt; Void) -&gt; Bool {<br>    // Extract the data from userActivity<br>    if let incomingURL = userActivity.webpageURL {<br>        let params = incomingURL.queryParameters <br>        let path = incomingURL.path<br>				print(params)<br>				print(path)<br>        // We can now use extracted data to navigate or perform actions in the app<br>    }<br>    return true<br>}</pre><p>It’s vital to ensure the app responds properly to the Universal Links by extracting and processing the data from <strong><em>userActivity</em></strong> variable***.***</p><p>Now, you might be wondering what happens if a user clicks a Universal Link associated with an app which isn’t installed on their device…</p><h3>Setting up a fallback mechanism</h3><p>In the event a user clicks a Universal Link for an app they don’t have installed, it’s important to implement a fallback mechanism to handle such situations.</p><p>Let’s take a look:</p><pre>//Check if app is installed and then handle this case. <br>func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -&gt; Void) -&gt; Bool {<br>    // handle the Universal Link<br>    if let incomingURL = userActivity.webpageURL {<br>        if appIsInstalled {<br>            // Handle the Universal Link in the app and perform desired activity<br>            handleUniversalLink(url: incomingURL)<br>        } else {<br>            // Fallback mechanism for when the app is not installed in device, take user to app store<br>            redirectToAppStore()<br>        }<br>    }<br>    return true<br>}</pre><p>Here we’ve checked whether the app is installed before attempting to process the Universal Link provided a fallback redirecting the users to the App Store to download the app.</p><h3>Testing Universal Links</h3><p>Of course, when using Universal Links (or any other tool for that matter) it’s crucial we test them to detect and fix any issues before going into production. Let’s take a look at some ways we can test Universal Links.</p><h3>Apple Validation Tool</h3><p>We can use the Apple Validation Tool to check the format, structure, and validity of our Apple App Site Association (AASA) file. To do this we simply follow these steps:</p><ol><li>Upload the AASA file to the Apple Validation Tool</li><li>Verify the file is in the correct format and conforms to Apple’s specifications</li><li>Confirm the file is accessible from the web by checking its availability and status</li></ol><p>Once validation is complete we’ll need to check the file is ready to be utilised by iOS devices to establish associations between the web and the iOS app.</p><h3>Testing on physical devices</h3><p>Universal Links should be tested on physical devices to ensure they behave as expected in real-world scenarios. We should carry out testing with app both installed and uninstalled to make sure both the links and fallbacks are working properly.</p><p><strong>Installed testing:</strong></p><p>To test with the app installed, follow these steps:</p><ol><li>Install the app on a real iOS device</li><li>Trigger the Universal Link from the web page and verify if the app launches and handles the links properly</li><li>Check if the data extraction from the Universal Link is working as expected</li></ol><p><strong>Uninstalled testing:</strong></p><p>And to test with the app not installed, it’s these steps:</p><ol><li>Confirm the app is not installed on your test device</li><li>Trigger the Universal Link from web and confirm that the fallback mechanism is working and redirecting the users to the App Store or a relevant web page</li><li>Test the deep linking scenarios to confirm if users are directed to specific screen within your app when not installed</li></ol><p>Fantastic, now we can set up Universal Links and test them, let’s take a look at some of the common issues and how they can be resolved.</p><h3>Troubleshooting</h3><p>As Universal Links have multiple dependencies within both the website and app, there are more possibilities for issues to arise affecting the performance of the links. We’ll take a look at some of the most common issues now.</p><h3>Redirects</h3><p>Redirects in our URL might cause problems for Universal Links so it’s important they are properly handled in our app. Some redirects may interfere with the Universal Link flow which will lead to some unexpected behaviour.</p><p>To protect against this we can implement a logic to follow the redirects and ensure that the final destination URL is handled properly, as demonstrated below:</p><pre>//Code to handle the redirects <br>func handleRedirections(for url: URL) {<br>    // Follow the redirects and obtain the final destination URL<br>    let finalURLs = resolveRedirects(for: url)</pre><pre>    // Now Handle the final URL properly<br>    handleUniversalLinks(url: finalURLs)<br>}</pre><h3>App IDs and Team IDs</h3><p>We’ll need to confirm the App IDs and Team IDs are correct to ensure Universal Links work in application. We should also verify that the specified App ID and Team ID match those assigned in the Xcode project settings in the Apple Developer portal and the AASA file.</p><p>To do this, follow these steps:</p><ol><li>In <strong>Xcode</strong>: check the Bundle id and Team in General Settings</li><li>In the <strong>AASA file:</strong> ensure that the App ID and Team ID fields are correct</li></ol><p>If there’s a mismatch or incorrect IDs the Universal Links will not function correctly, leading to failures in navigation between the web page and the app.</p><h3>Case Sensitivity of URLs</h3><p>URLs are case sensitive, and if there is any inconsistencies in the URL scheme configuration will lead to errors and the URL will not function as expected.</p><p>It’s vital to check all URLs and associated ids, like Bundle Id, App id, and TeamID, are in the correct case across all configuration files, including the AASA file and Xcode project settings. See the example below:</p><pre>// Example how AASA looks in JSON format<br>{<br>    &quot;applinks&quot;: {<br>        &quot;apps&quot;: [],<br>        &quot;details&quot;: [<br>            {<br>                &quot;appID&quot;: &quot;DFGS12345.com.bugfender.app&quot;,<br>                &quot;paths&quot;: [&quot;/paths&quot;]<br>            }<br>        ]<br>    }<br>}</pre><h3>Privacy and permissions</h3><p>User privacy is and incredibly important consideration when implementing Universal Links and it’s crucial to explicitly ask for permission before opening the mobile app from a tapped Universal Link. By asking permission in advance we’re respecting the user’s privacy and creating a more trustworthy and user friendly experience.</p><p>We’ll need to present a permission popup when a Universal Link is tapped, explaining the action our app will take with an action button for to grant or deny the permission. It’s important to clearly communicate the benefits of the Universal Link and that improves the user experience.</p><p>Here’s a demonstration:</p><pre>// show a permission prompt to the user when link is clicked.<br>func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -&gt; Void) -&gt; Bool {<br>    // Display permission prompt in App<br>    showPermissionsPrompt { granted in<br>        if granted {<br>            // Handle the Universal Link<br>            handleUniversalLinks(url: userActivity.webpageURL)<br>        } else {<br>            // Handle the denial or fallback<br>            redirectToWebPage()<br>        }<br>    }<br>    return true<br>}</pre><p>Using clear language and a simple flow will increase our chances of gaining the users permission.</p><p>We also need to enable users to manage their preferences regarding Universal Links in the app settings, allowing them to revoke or grant permission at any point and time.</p><h3>Best Practice</h3><p>Let’s now take a look at some best practice when using Universal Links.</p><h3>User experience</h3><p>Here are some things to consider to ensure a smooth and satisfying user experience:</p><ul><li><strong>Loading time:</strong> Loading time for both the web and app screens should be kept to a minimum to provide a smooth and responsive experience.</li><li><strong>Design language:</strong> A consistent look and feel (e.g. color schemes and branding) should be maintained between the web and app screens to provide a seamless transition between the two</li><li><strong>Navigation:</strong> As with the look and feel, navigation should be consistent between the web and app so users can progress easily in the new environment.</li></ul><h3>AASA file updates</h3><p>The AASA file is the most essential component of a Universal Link and should be regularly checked and updated. This is to ensures any new domains are appropriately associated with the app and any configuration changes are reflected properly:</p><ul><li><strong>Web domains:</strong> If a new web domain is introduced that should be linked to the app we’ll need to update the AASA file accordingly to ensure the Universal Links continue to function as they should.</li><li><strong>Configuration:</strong> Changes to system configuration (e.g. updates to the web functionality or adding sub domains) will also need to be reflected in the AASA file.</li><li><strong>Version control:</strong> It’s a good idea to keep a record of different versions of the AASA file to help in troubleshooting and rollback if any issues arise after changes are made.</li></ul><h3>Advanced resources and further reading</h3><p>Hungry for more? Detailed information on Universal Links in iOS apps is available on <a href="https://developer.apple.com/documentation/xcode/allowing-apps-and-websites-to-link-to-your-content?language=swift">**Apple’s official documentation</a>** which ****provides comprehensive guidance, best practices and technical details related to the Universal Links.</p><p><a href="https://developer.apple.com/videos/play/wwdc2020/10098/">https://developer.apple.com/videos/play/wwdc2020/10098/</a></p><p>It’s important to regularly check the documentation for updates or additional features for Universal Links that may be introduced from time-to-time. Additionally we can find valuable insights and troubleshooting tips in the community forums, developer blogs, and related iOS development resources on web.</p><h3>To sum up</h3><p>We’ve looked at the multiple benefits Universal Links, how a Universal Link differs form a deep link and what they can offer to app developers including:</p><ul><li>User experience</li><li>App engagement and retention</li><li>Analytics and insight</li></ul><p>We’ve also worked through setting up Universal Links, including:</p><ul><li>Creating and hosting an AASA file</li><li>Configuring associated domains</li><li>Handling Universal Links and extracting data from UserActivity</li><li>Setting up fallback mechanisms</li><li>Testing, both simulated and real-world</li></ul><p>We also looked at some of the other crucial things to understand about Universal Links, including:</p><ul><li>Privacy and permissions</li><li>Best practice</li></ul><p>We hope you’ve found this guide to Universal Links informative and have confidence to experiment with them in your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec475d06e5ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apple’s New Privacy Requirements in the App Store]]></title>
            <link>https://medium.com/@sachinsiwal/apples-new-privacy-requirements-in-the-app-store-92fb5b3e8a32?source=rss-960245db539e------2</link>
            <guid isPermaLink="false">https://medium.com/p/92fb5b3e8a32</guid>
            <category><![CDATA[apple-privacy]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Ch. Sachin Siwal]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 08:39:16 GMT</pubDate>
            <atom:updated>2024-07-16T08:00:43.105Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Privacy manifest file requirement</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*diti5doJOW35awIiM60cSg.png" /><figcaption><a href="https://bugfender.com/blog/apple-privacy-requirements/">Privacy manifest file requirement</a></figcaption></figure><h3>Introduction</h3><p>One of the <a href="https://bugfender.com/blog/apple-privacy-requirements/">latest changes introduced by Apple</a> is that developers needs to describe the data your app or third-party SDK collects and provide the required reasons of the APIs it uses.</p><p>You might be interested in reading:</p><p><a href="https://bugfender.com/blog/swift-backend/"><strong><em>Swift as a Backend</em></strong></a> &amp; <a href="https://bugfender.com/blog/swift-backend-best-practices/"><strong><em>Best Practices to Use Swift For Backend</em></strong></a></p><p><a href="https://bugfender.com/blog/swift-machine-learning-using-apple-core-ml/"><strong><em>Machine learning in Swift iOS — A step by step guide</em></strong></a></p><p>To do so, applications and third-party SDKs that are distributed as XCFrameworks, Swift packages, or Xcode projects, need to contain a privacy manifest file, named PrivacyInfo.xcprivacy.</p><p>⚠️ <strong>Starting May 1, 2024, apps that don’t describe their use of required reason API in their privacy manifest file aren’t accepted by App Store Connect.</strong></p><p>The privacy manifest file is a property list (plist) that records the types of data collected by your app, and for each required reasons API in your app or third-party SDK, it reports the reason for its usage.</p><p>You need to include a privacy manifest file in your third-party SDK if it’s listed in “SDKs that require a privacy manifest and signature,” in <a href="https://developer.apple.com/support/third-party-SDK-requirements/">Upcoming third-party SDK requirements</a>. Otherwise, include a privacy manifest file in your third-party SDK if it uses a required reasons API or collects data about the person using apps where the third-party SDK will be used.</p><p><strong>You might be receiving these emails from Apple after submitting a build on TestFlight:</strong></p><p>Although the TestFlight submission was successful, it’s recommended that you correct the issues in your next submission for TestFlight review.</p><blockquote><strong><em>ITMS-91053: Missing API declaration</em></strong><em> — Your app’s code in the “AppName” file references one or more APIs that require reasons, including the following API categories: NSPrivacyAccessedAPICategoryFileTimestamp. While no action is required at this time, starting May 1, 2024, when you upload a new app or app update, you must include a NSPrivacyAccessedAPITypes array in your app’s privacy manifest to provide approved reasons for these APIs used by your app’s code. For more details about this policy, including a list of required reason APIs and approved reasons for usage, visit: </em><a href="https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api"><em>https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api</em></a><em>.</em></blockquote><blockquote><strong><em>ITMS-91053: Missing API declaration</em></strong><em> — Your app’s code in the “AppName” file references one or more APIs that require reasons, including the following API categories: NSPrivacyAccessedAPICategoryUserDefaults. While no action is required at this time, starting May 1, 2024, when you upload a new app or app update, you must include a NSPrivacyAccessedAPITypes array in your app’s privacy manifest to provide approved reasons for these APIs used by your app’s code. For more details about this policy, including a list of required reason APIs and approved reasons for usage, visit: </em><a href="https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api"><em>https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api</em></a><em>.</em></blockquote><blockquote><strong><em>ITMS-91053: Missing API declaration</em></strong><em> — Your app’s code in the “AppName” file references one or more APIs that require reasons, including the following API categories: NSPrivacyAccessedAPICategorySystemBootTime. While no action is required at this time, starting May 1, 2024, when you upload a new app or app update, you must include a NSPrivacyAccessedAPITypes array in your app’s privacy manifest to provide approved reasons for these APIs used by your app’s code. For more details about this policy, including a list of required reason APIs and approved reasons for usage, visit: </em><a href="https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api"><em>https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api</em></a><em>.</em></blockquote><blockquote><strong><em>ITMS-91053: Missing API declaration</em></strong><em> — Your app’s code in the “AppName” file references one or more APIs that require reasons, including the following API categories: NSPrivacyAccessedAPICategoryDiskSpace. While/ no action is required at this time, starting May 1, 2024, when you upload a new app or app update, you must include a NSPrivacyAccessedAPITypes array in your app’s privacy manifest to provide approved reasons for these APIs used by your app’s code. For more details about this policy, including a list of required reason APIs and approved reasons for usage, visit: </em><a href="https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api"><em>https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api</em></a><em>.</em></blockquote><h3>How to create a privacy manifest</h3><p>These are the steps add the privacy manifest to your app or third-party SDK in Xcode, follow these steps:</p><ul><li>Choose File &gt; New File.</li><li>Scroll down to the Resource section, and select App Privacy File type.</li><li>Click Next.</li><li>Check your app or third-party SDK’s target in the Targets list.</li><li>Click Create.</li></ul><p>By default, the file is named PrivacyInfo.xcprivacy; this is the required file name for bundled privacy manifests.</p><p>You need to add the privacy manifest file to your target’s resources for Xcode to use it when you generate a privacy report. If you distribute your third-party SDK as a static library, use the support for static frameworks in Xcode 15 or later to bundle resources, including the privacy manifest file. Create a framework target in Xcode that builds your product, set its Mach-O type build setting to “Static Library,” and add the privacy manifest file to your target’s bundle resources along with any other resources, for example, image files.</p><p><strong>At the top level of this property list file, add the following keys to the dictionary:</strong></p><p>NSPrivacyTrackingA Boolean that indicates whether your app or third-party SDK uses data for tracking as defined under the App Tracking Transparency framework.</p><p>NSPrivacyTrackingDomainsAn array of strings that lists the internet domains your app or third-party SDK connects to that engage in tracking. If the user has not granted tracking permission through the App Tracking Transparency framework, network requests to these domains fail and your app receives an error. If you set NSPrivacyTracking to true then you need to provide at least one internet domain in NSPrivacyTrackingDomains; otherwise, you can provide zero or more domains.</p><p>NSPrivacyCollectedDataTypesAn array of dictionaries that describes the data types your app or third-party SDK collects. For information on the keys and values to use in the dictionaries, see Describing data use in privacy manifests.</p><p>NSPrivacyAccessedAPITypesAn array of dictionaries that describe the API types your app or third-party SDK accesses that have been designated as APIs that require reasons to access.</p><h3>Describing use of required reason API</h3><p>Some APIs in your app may be misused for device fingerprinting, which is not permitted even if users consent to tracking. Apple requires apps to describe the reasons for using certain APIs in their privacy manifest files. Failure to do so may lead to rejection from the App Store. Apps using required reason APIs must declare approved reasons for their use and may only use the APIs for the stated purposes. It is essential to accurately report the use of APIs in the privacy manifest files for both apps and third-party SDKs. Third-party SDKs cannot rely on apps or other SDKs to report their usage of required reason APIs.</p><p>You can see all the specific details in the following Apple article:</p><p><a href="https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api">https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api</a></p><p>The sections below outline the various categories of required reason APIs, specify the APIs within each category, and detail the permissible reasons that can be incorporated into a privacy manifest.</p><h3>Summary of required reason APIs</h3><p><strong>File timestamp APIs</strong></p><p>Require reasons for accessing creationDate, modificationDate, fileModificationDate, contentModificationDateKey, and other related functions. Declare reasons like displaying file timestamps, accessing metadata within the app container, or user-granted directories. Use specific reason codes for third-party SDKs or displaying timestamps to users without sending information off-device.</p><p><strong>System boot time APIs</strong></p><p>The usage of functions like systemUptime and mach_absolute_time(), need reasons for use, such as measuring time between app events or calculating timestamps. Declare reasons for app functionality or optional bug reports with considerations for data usage. Ensure prominence in bug reports and adherence to user choices for sending information off-device.</p><p><strong>Disk space APIs</strong></p><p>Including volume and system capacities, require explicit declaration for displaying disk space, managing file storage, or optional bug reports. Declare reasons based on app behavior, low disk space impact in health research apps, and user-initiated bug report submissions. Adhere to permission protocols for sending disk space details, avoiding unnecessary downloads, and informative bug report inclusions.</p><p><strong>Active keyboard APIs</strong></p><p>Need reasons for determining activeInputModes, essential for custom keyboard apps or user interface personalization. Declare reasons for primary app functionality, user interface adjustments, and ensuring active keyboard data remains on the device without transmission.</p><p><strong>User defaults APIs</strong></p><p>Usage of functionality like UserDefaults, require declaration to access app-specific information. Declare reasons for reading and writing app-restricted data, app group exclusivity, or third-party SDK functionality. Access managed app configurations or feedback stored under specific key sets for Mobile Device Management compatibility, ensuring compliance with the Apple protocol.</p><h3>Example Privacy Info file</h3><p>Here is a sample file that you can directly download and use in your project, you can later update it based on your needs. This PrivacyInfo.xcprivacy file specifies four API categories accessed by an application, each associated with a unique reason code. These include access to user preferences (NSPrivacyAccessedAPICategoryUserDefaults) with reason code <strong>CA92.1</strong>, monitoring of disk space usage (NSPrivacyAccessedAPICategoryDiskSpace) with reason code <strong>7D9E.1</strong>, retrieval of file timestamps (NSPrivacyAccessedAPICategoryFileTimestamp) with reason code <strong>3B52.1</strong>, and checking the system&#39;s boot time (NSPrivacyAccessedAPICategorySystemBootTime) with reason code <strong>35F9.1</strong>.</p><p><a href="https://prod-files-secure.s3.us-west-2.amazonaws.com/deab8967-3c9f-42e5-91ba-d7b5b5bdb2a0/26246a72-5fbd-427d-9db8-6b28ac65326d/PrivacyInfo.xcprivacy">PrivacyInfo.xcprivacy</a></p><h3>Describing the data your app or third-party SDK collects</h3><p>Once you have your PrivacyInfo file, it’s time to provide a description of all the data your app collects. To do so, for each type of data your app or third-party SDK collects, you will need to add a dictionary to the NSPrivacyCollectedDataTypes array in your privacy information file. You will need to add the following keys to the dictionary.</p><p>NSPrivacyCollectedDataType A string that identifies the type of data your app or third-party SDK collects.</p><p>NSPrivacyCollectedDataTypeLinkedA Boolean that indicates whether your app or third-party SDK links this data type to the user’s identity.</p><p>NSPrivacyCollectedDataTypeTrackingA Boolean that indicates whether your app or third-party SDK uses this data type to track.</p><p>You can see all categories and and valid values in the official Apple documentation:</p><p><a href="https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_data_use_in_privacy_manifests">https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_data_use_in_privacy_manifests</a></p><h3>Create your app’s privacy report</h3><p>Xcode can create a privacy report by aggregating the privacy manifests from your app and the third-party SDKs it links to. Use the privacy report to better understand all of the data collected by your app and whether it tracks. Create the privacy report for your app by doing the following:</p><ol><li>Open your project in Xcode.</li><li>Choose <strong>Product</strong> &gt; <strong>Archive</strong>. Xcode creates the archive and reveals it in the organizer.</li><li>Control-click the archive in the organizer and choose <strong>Generate Privacy Report</strong>.</li><li>Choose a location to save the privacy report.</li><li>Switch to Finder.</li><li>Navigate to the location where you saved the privacy report, and double-click to open the report in Preview.</li></ol><p>App extensions don’t include privacy information files. The operating system and App Store Connect use the privacy information file in the extension’s host app bundle, in combination with those from third-party SDKs your app links to.</p><h3>User Privacy and Data Use in Bugfender</h3><p>In case you use Bugfender to collect logs and crashes from your users, you might be concerned about Bugfender’s use of data on your application. If this is the case, you can be safe because:</p><ul><li>Bugfender does not track your users across apps or websites.</li><li>Bugfender does not use your user’s data for their own purposes, nor sell it to third parties, for advertisement purposes, nor any other purposes.</li><li>Bugfender does not access the device’s advertising identifier (IDFA) nor the ID for Vendors (IDFV).</li><li>If you’re developing an iOS application, you do not need to ask the user for permission with the <strong>AppTrackingTransparency</strong> framework, since Bugfender does not do “tracking” in the definition of Apple in connection with advertising.</li><li>If you gather personal data with Bugfender, you can sign a <a href="https://support.bugfender.com/en/articles/1538086-personal-data-processing-agreement-dpa-and-gdpr-compliance">Data Processing Agreement</a> with us, so that you and your users are protected under GDPR.</li></ul><p>At Bugfender we take security and privacy very seriously, if you want to read more about security related topics you can check our <a href="https://support.bugfender.com/en/collections/230028-security-and-compliance">Bugfender Security and Compliance knowledge base</a>.</p><h3>Nutrition Labels for the App Store</h3><p>As mentioned, Bugfender does not track users, and by default collects a minimal set of information about the device (see <a href="https://support.bugfender.com/en/articles/2715330-which-device-data-is-automatically-collected-from-users">Which device data is automatically collected from users?</a>).</p><p>Out of the categories Apple indicates, Bugfender collects:</p><ul><li>Other Diagonstic Data, since you use Bugfender to collect application logs and crashes. This information is not linked to the user and not used for tracking.</li></ul><p>The Bugfender iOS SDK already includes a .xcprivacy file with this statement since version 1.13.0. So if you are using this or a later version of the iOS SDK, you are safe with the new Apple requirements.</p><p>Please note you may be collecting additional data with the help of Bugfender (your user’s name, email, etc.), and you may be using it for additional reasons (analytics, product personalization, etc.). Also you may be linking this data to the user by adding custom key-values and using the data for tracking. If that’s the case, you’re responsible for declaring these uses of information in App Store Connect or your application’s .xcprivacy file.</p><p>Look out for the following:</p><ul><li>Product Interaction, if you enable automated UI logging or if you do manual logging to track interactions.</li><li>Crash Data, if you enable crash reporting.</li><li>Performance data, if you log anything related with performance.</li><li>Identifiers, if you use custom device key-values to associate the logs of a device with its owner or the device itself.</li></ul><h3>Conclusion</h3><p>Proper implementation of Privacy — the manifest file is the key to following Apple’s privacy guidelines. Transparent declaration of API usage can build more trust for the user while helping in meeting those set by regulations. Stay updated with the documents provided by Apple in a bid to always remain compliant as standards change.</p><p>We discussed about the Data collections and declaration of what is being collected and for what reason. All Keys with reason and description are detailed in this article.</p><p>Remember that Privacy accessed APIs are mandatory from May 01, 2024 to submit the apps on App store. These APIs are mainly related to the use of UserDefault API, System boot time, FileTimestamp and Disk Space. All listed apis and functions, if used in your App or third-party SDK, need to specify the reason of use.</p><p>Privacy is the utmost concern of Apple for it’s users and Apple try to maintain the highest level of security, privacy and trust of it’s users to use it’s products. These API’s will help users know the upfront, what all data will be collected by the app and why and where that data will be used.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92fb5b3e8a32" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>