<?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 Bevan christian on Medium]]></title>
        <description><![CDATA[Stories by Bevan christian on Medium]]></description>
        <link>https://medium.com/@bevanchristian?source=rss-1cd75752f934------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-K0S7q_XBZUTy7iAsgt6UA.jpeg</url>
            <title>Stories by Bevan christian on Medium</title>
            <link>https://medium.com/@bevanchristian?source=rss-1cd75752f934------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:25:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bevanchristian/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[How to Perfectly Merge SwiftUI and UIKit Navigation: A Step-by-Step Guide]]></title>
            <link>https://engineering.idn.media/how-to-perfectly-merge-swiftui-and-uikit-navigation-a-step-by-step-guide-cbae0275b760?source=rss-1cd75752f934------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbae0275b760</guid>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bevan christian]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 02:40:04 GMT</pubDate>
            <atom:updated>2024-08-07T02:40:04.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnrxTqFkWRvH8nK8vkeqHg.png" /></figure><p>Have you ever considered integrating SwiftUI into a legacy app built with UIKit? While UIHostingController provides a way to use SwiftUI in UIKit-based apps, this article will explore a more structured approach to navigation that mimics the NavigationStack system from UIKit.</p><p>Here’s an overview of how to implement seamless navigation between SwiftUI and UIKit:</p><h4>Navigating in SwiftUI</h4><p>To illustrate navigation in SwiftUI, consider the following code example:</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    var body: some View {<br>        NavigationView {<br>            List(items) { item in<br>                NavigationLink(destination: DetailView(item: item)) {<br>                    Text(item.name)<br>                }<br>            }<br>            .navigationTitle(&quot;Items&quot;)<br>        }<br>    }<br>}<br><br>struct DetailView: View {<br>    var item: Item<br><br>    var body: some View {<br>        VStack {<br>            Text(item.name)<br>                .font(.largeTitle)<br>                .padding()<br><br>            Text(item.description)<br>                .padding()<br><br>            Spacer()<br>        }<br>        .navigationTitle(&quot;Detail&quot;)<br>    }<br>}</pre><p>In this example, ContentView uses a NavigationView to create a list of items. Tapping on an item navigates to DetailView, which displays more information about the selected item.</p><h3><strong>Old Way Navigating from SwiftUI to UIKit </strong>and vice versa</h3><p>To integrate SwiftUI with UIKit and vice versa, consider these methods:</p><p><strong>Using </strong><strong>UIViewControllerRepresentable:</strong></p><ul><li>This protocol allows you to wrap a UIViewController in a SwiftUI view, enabling you to present UIKit view controllers from SwiftUI.</li></ul><p><strong>Using </strong><strong>UIHostingController:</strong></p><ul><li>Conversely, you can present SwiftUI views from UIKit by wrapping them in a UIHostingController.</li></ul><pre>struct MySwiftUIView: View {<br>    var body: some View {<br>        VStack {<br>            Text(&quot;Hello from SwiftUI!&quot;)<br>                .font(.largeTitle)<br>            NavigationLink(&quot;Go Back to UIKit&quot;, destination: UIKitViewControllerRepresentable())<br>        }<br>        .navigationTitle(&quot;SwiftUI View&quot;)<br>    }<br>}<br><br>// SwiftUI view that represents UIKit view controller<br>struct UIKitViewControllerRepresentable: UIViewControllerRepresentable {<br>    func makeUIViewController(context: Context) -&gt; AnotherUIKitViewController {<br>        return AnotherUIKitViewController()<br>    }<br><br>    func updateUIViewController(_ uiViewController: AnotherUIKitViewController, context: Context) {<br>        // Update the view controller if needed<br>    }<br>}</pre><p>In this code snippet, MySwiftUIView uses NavigationLink to navigate to a SwiftUI view that wraps a UIKit view controller using UIKitViewControllerRepresentable.</p><h3><strong>Problem With Old Way</strong></h3><ol><li>Navigation logic is embedded within the view.</li><li>Navigation is tightly coupled to the code provided by SwiftUI.</li><li>There’s inconsistency in navigation between UIKit and SwiftUI modules, resulting in two distinct navigation methods within the app.</li><li>The team needs to grasp both UIViewControllerRepresentable and UIHostingController, adding complexity.</li></ol><h3>Simplifying Navigation with Routers</h3><p>For a more seamless and organized approach, you can set up a router class to manage navigation between SwiftUI and UIKit views. This approach ensures a clean separation of concerns and provides a consistent navigation experience. Additionally, it allows us to ensure that all navigation leverages the existing UIKit system.</p><p>Here’s a graph to help visualize our objective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*MFSpjlr6Vy3P4M-eyWv6EQ.png" /></figure><h4>Navigational Flow</h4><p><strong>ProfileView to ProfileViewModel</strong>:</p><ul><li>When a user interacts with ProfileView (e.g., tapping a button), the view model (ProfileViewModel) is triggered to perform specific actions. This interaction is represented by action flows in the graph.</li></ul><p><strong>ProfileViewModel to ProfileSwiftUIRouter</strong>:</p><ul><li>The view model processes the actions and requests the router (ProfileSwiftUIRouter) to handle navigation. This includes routing to UIKit view controllers, presenting SwiftUI modals, or pushing SwiftUI views onto the navigation stack.</li></ul><p><strong>ProfileSwiftUIRouter to Views</strong>:</p><p>The router manages the actual navigation based on the requests from the view model. It can:</p><p>1. Push or present UIKit view controllers.</p><p>2. Present SwiftUI views as modals using UIHostingController.</p><p>3. Push additional SwiftUI views on the navigation stack.</p><p>First, we can prepare a router class for all our views, whether they are SwiftUI or UIKit</p><h3>Implementing Navigation</h3><h4>Setting Up the Router</h4><p>The ProfileSwiftUIRouter class handles the navigation and presentation for both SwiftUI and UIKit components. Here’s how it works:</p><p><strong>Protocols and Delegates</strong></p><pre>protocol ProfileSwiftUIRouterrDelegate: AnyObject {<br>    func openPopup(popup: UIViewController)<br>    func closePage()<br>    func closeSheet(completion: (() -&gt; Void)?)<br>    func route(destination: UIViewController)<br>}</pre><p>This protocol defines methods for managing navigation actions such as opening popups, closing pages, or routing to different view controllers.</p><p><strong>Router Implementation</strong></p><pre>class ProfileSwiftUIRouter: ProfileSwiftUIRouterrDelegate {<br>    <br>    var viewController: UIHostingController&lt;YourSwiftUIView&gt;?<br>    <br>    static func createModule() -&gt; UIViewController {<br>        let router = ProfileSwiftUIRouter()<br>        let viewModel = ProfileViewModel(router: router)<br>        let swiftUIView = ProfileView(viewModel: viewModel)<br>        let viewController = UIHostingController(rootView: swiftUIView)<br>        router.viewController = viewController<br>        return viewController<br>    }<br>    <br>    func openPopup(popup: UIViewController) {<br>        viewController?.present(popup, animated: true, completion: nil)<br>    }<br>    <br>    func closePage() {<br>        viewController?.navigationController?.popViewController(animated: true)<br>    }<br>    <br>    func route(destination: UIViewController) {<br>        viewController?.navigationController?.pushViewController(destination, animated: true)<br>    }<br>    <br>}</pre><ul><li><strong>viewController</strong>: Holds a reference to the UIHostingController that hosts the SwiftUI view.</li><li><strong>createModule()</strong>: Creates a module consisting of a SwiftUI view and its view model, setting up the router to handle navigation.</li><li><strong>openPopup(popup:)</strong>: Presents a modal view controller.</li><li><strong>closePage()</strong>: Pops the current view controller off the navigation stack.</li><li><strong>route(destination:)</strong>: Pushes a new view controller onto the navigation stack.</li></ul><blockquote>But you must ensure that when `<strong>ProfileSwiftUIRouter</strong>` creates the module, it gets pushed by a view that already has a navigation controller.</blockquote><pre> func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {<br>        guard let windowScene = (scene as? UIWindowScene) else { return }<br>        <br>        let profileVCRevamp = UINavigationController(rootViewController: ProfileSwiftUIRouter.createModule())<br>        <br>        let window = UIWindow(windowScene: windowScene)<br>        window.rootViewController = profileVCRevamp<br>        self.window = window<br>        window.makeKeyAndVisible()<br>  }</pre><p>)</p><h4>How It Works Together</h4><ul><li><strong>Router-ViewModel Communication</strong>: The ProfileViewModel is initialized with the router, allowing it to trigger navigation actions while focusing on business logic and state management.</li><li><strong>UIHostingController</strong>: This wraps the SwiftUI view (ProfileView) inside a UIKit UIViewController, enabling the integration of SwiftUI views within a UIKit-based app.</li></ul><p>By adopting this approach, you maintain a clean architecture and smoothly integrate SwiftUI into your existing UIKit-based application. Meanwhile, if navigation is from SwiftUI to UIKit, there’s no need for UIViewControllerRepresentable because everything uses navigationController.</p><p>The router acts as a centralized navigation controller, managing the transitions between views and handling modal presentations, which is crucial for maintaining a clean architecture as the app grows in complexity.</p><h3>ViewModel</h3><p>This code sets up a ProfileViewModel that is responsible for handling navigation actions within an app that uses both SwiftUI and UIKit. The ViewModel uses routers to manage navigation to different views.</p><p><strong>ProfileViewModel with Router Injection</strong></p><pre>class ProfileViewModel: ObservableObject {<br>    <br>    var router: ProfileSwiftUIRouter?  <br>    init(router: ProfileSwiftUIRouter?) {<br>        self.router = router<br>    }<br><br>    // Push UIKit View<br>    func moveToDetail() {<br>        let vc = DetailViewControllerRouter.createModule()<br>        router?.route(destination: vc)<br>    }<br>    // Open SwiftUI Modal<br>    func openSwiftUIModal() {<br>        let popupView = PopupLevelChangeLandscapeView(viewModel: viewModel)<br>        let popupViewController = UIHostingController(rootView: popupView)<br>        router?.openPopup(popup: popupViewController)<br>    }<br>    // Push SwiftUI View<br>    func pushSwiftUIView() {<br>        let nextCV = DetailSwiftUIViewRouter.createModule()<br>        router?.route(destination: nextCV)<br>    }<br>}</pre><p><strong>Router Injection</strong>: The view model is initialized with a router, enabling it to manage navigation.</p><p><strong>Navigation Actions</strong>:</p><ul><li><strong>moveToDetail()</strong>: Routes to a UIKit view controller.</li><li><strong>openSwiftUIModal()</strong>: Presents a SwiftUI modal view.</li><li><strong>pushSwiftUIView()</strong>: Pushes a new SwiftUI view.</li></ul><p><strong>DetailViewControllerRouter (SwiftUI View)</strong></p><pre>class DetailSwiftUIViewRouter {<br>    <br>    var viewController: UIHostingController&lt;DetailSwiftUIView&gt;?<br>    <br>    static func createModule() -&gt; UIViewController {<br>        let router = DetailSwiftUIViewRouter()<br>        let DetailSwiftUIViewModel = DetailSwiftUIViewModel(router: router)<br>        let view = DetailSwiftUIView(viewModel: DetailSwiftUIViewModel)<br>        let viewController = UIHostingController(rootView: view)<br>        viewController.hidesBottomBarWhenPushed = true<br>        router.viewController = viewController<br>        return viewController<br>    }<br>}</pre><ul><li><strong>DetailSwiftUIViewRouter</strong>: This router handles the creation and navigation of a SwiftUI view (DetailSwiftUIView). It uses UIHostingController to wrap the SwiftUI view, enabling it to be used in a UIKit-based navigation flow.</li></ul><p><strong>DetailViewControllerRouter (UIKit View)</strong></p><pre>class DetailViewControllerRouter {<br>    <br>    var viewController: DetailViewController?<br><br>     static func createModule() -&gt; UIViewController {<br>        let router = DetailViewControllerRouter()<br>        let detailViewModel = DetailViewModel(router: router)<br>        let viewController = DetailViewController(viewModel: detailViewModel)<br>        router.viewController = viewController<br>        return viewController<br>    }<br>}</pre><ul><li><strong>DetailViewControllerRouter</strong>: This router handles the creation and navigation of a UIKit view (DetailViewController). It follows a similar pattern to the SwiftUI router, creating the view controller and linking it to its ViewModel.</li></ul><p>The ProfileViewModel uses injected routers to manage navigation across different views, both in SwiftUI and UIKit. This approach keeps navigation logic separate from the view models, making the code more modular and easier to maintain. The routers (DetailSwiftUIViewRouter and DetailViewControllerRouter) are responsible for creating and managing their respective views, ensuring that the view model can focus on business logic rather than navigation details.</p><h3>View SwiftUI</h3><pre>struct ProfileView: View {<br>    @ObservedObject var viewModel: ProfileViewModel<br><br>    var body: some View {<br>        VStack(spacing: 20) {<br>            Button(action: {<br>                viewModel.moveToDetail()<br>            }) {<br>                Text(&quot;Go to Detail (UIKit)&quot;)<br>                    .font(.headline)<br>                    .padding()<br>                    .background(Color.blue)<br>                    .foregroundColor(.white)<br>                    .cornerRadius(8)<br>            }<br><br>            Button(action: {<br>                viewModel.openSwiftUIModal()<br>            }) {<br>                Text(&quot;Open SwiftUI Modal&quot;)<br>                    .font(.headline)<br>                    .padding()<br>                    .background(Color.green)<br>                    .foregroundColor(.white)<br>                    .cornerRadius(8)<br>            }<br><br>            Button(action: {<br>                viewModel.pushSwiftUIView()<br>            }) {<br>                Text(&quot;Push SwiftUI View&quot;)<br>                    .font(.headline)<br>                    .padding()<br>                    .background(Color.orange)<br>                    .foregroundColor(.white)<br>                    .cornerRadius(8)<br>            }<br>        }<br>        .padding()<br>        .navigationTitle(&quot;Revamp Profile&quot;)<br>    }<br>}</pre><p><strong>@ObservedObject</strong>: Allows the view to react to changes in the view model.</p><p><strong>Buttons</strong>:</p><ul><li><strong>“Go to Detail (UIKit)”</strong>: Calls moveToDetail() to navigate to a UIKit view.</li><li><strong>“Open SwiftUI Modal”</strong>: Calls openSwiftUIModal() to present a SwiftUI modal.</li><li><strong>“Push SwiftUI View”</strong>: Calls pushSwiftUIView() to push a new SwiftUI view.</li></ul><p>In this setup, the ProfileView delegates navigation responsibilities to the ProfileViewModel, which uses the ProfileSwiftUIRouter to manage navigation. This approach keeps navigation logic modular and separate from the view models, ensuring that each component focuses on its core responsibilities. The integration of SwiftUI with UIKit is seamless, allowing for a smooth transition between the two frameworks in a hybrid app environment.</p><h3>View UIKit</h3><p>In the ProfileViewController, we define a method, pushButtonTapped, that interacts with the ViewModel to navigate to a new SwiftUI view.</p><pre>class ProfileViewController: UIViewController {<br>var viewModel: ProfileViewModel!<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>    }<br>    // Action method called when the button is tapped<br>    @objc func pushButtonTapped() {<br>        viewModel.pushSwiftUIView()<br>    }<br>}</pre><p>This setup means ProfileViewController doesn&#39;t worry about whether it&#39;s navigating to a SwiftUI or UIKit view. Instead, it relies on the ViewModel to handle the navigation, keeping the process consistent and straightforward.</p><p>By centralizing navigation logic in the ViewModel, we ensure that the view controller only needs to manage user actions, while the ViewModel takes care of the navigation details. This approach makes the navigation experience seamless across both UIKit and SwiftUI, and it helps maintain a clean, organized codebase.</p><h3>Summary</h3><p>By offloading navigation logic to the ViewModel and Router, we maintain a clean and scalable architecture. This setup ensures that SwiftUI views remain focused on UI presentation while leveraging UIKit’s powerful navigation system. This approach simplifies managing complex navigation flows, especially in larger, hybrid applications.</p><h3>Key Objectives</h3><ol><li><strong>Seamless Integration</strong>: Facilitate smooth interaction and navigation between SwiftUI and UIKit views.</li><li><strong>Clean Architecture</strong>: Keep navigation logic within the router and business logic within the view model, maintaining clear separation of concerns.</li><li><strong>Consistent Navigation Experience</strong>: Ensure a uniform navigation experience whether transitioning between UIKit and SwiftUI or within the same framework.</li></ol><h3>Benefits</h3><ul><li><strong>Modular Codebase</strong>: The separation of navigation responsibilities from business logic enhances code modularity and maintainability.</li><li><strong>Enhanced Scalability</strong>: By integrating SwiftUI with UIKit, the application can leverage the strengths of both frameworks while managing a clear architecture.</li><li><strong>Unified Navigation</strong>: Utilizing UIKit’s UINavigationController for navigation in a SwiftUI-based app ensures consistent and seamless transitions.</li></ul><p>This approach effectively harnesses the strengths of both SwiftUI and UIKit, resulting in a more manageable and scalable codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbae0275b760" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/how-to-perfectly-merge-swiftui-and-uikit-navigation-a-step-by-step-guide-cbae0275b760">How to Perfectly Merge SwiftUI and UIKit Navigation: A Step-by-Step Guide</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goodbye pbxproj Conflicts: Simplify Your iOS Project with XcodeGen]]></title>
            <link>https://engineering.idn.media/goodbye-pbxproj-conflicts-simplify-your-ios-project-management-with-xcodegen-a45f750b7770?source=rss-1cd75752f934------2</link>
            <guid isPermaLink="false">https://medium.com/p/a45f750b7770</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcodegen]]></category>
            <category><![CDATA[package-management]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Bevan christian]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 07:22:56 GMT</pubDate>
            <atom:updated>2024-07-26T07:29:53.197Z</atom:updated>
            <content:encoded><![CDATA[<h3>Goodbye pbxproj Conflicts: Mastering Xcode Project Automation to Streamline Your Workflow with XcodeGen</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HtwwykRUhr9XkZep" /><figcaption>Photo by <a href="https://unsplash.com/@krishna2803?utm_source=medium&amp;utm_medium=referral">Krishna Pandey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>At IDN, <a href="https://medium.com/u/638ba0fb669f">Arnold Pangestu</a> , <a href="https://medium.com/u/160519e5795c">Rio Rizky Rainey F</a> and <a href="https://medium.com/u/1cd75752f934">Bevan christian</a> we’re adopting XcodeGen to make iOS project management simpler and more efficient. This tool helps us keep projects consistent, simplifies version control, and automates configuration, making our workflows smoother and better organized.</p><p>Managing Xcode project files can be challenging and prone to errors. XcodeGen is here to change that — it’s a powerful command-line tool that automatically generates Xcode project files from YAML or JSON specs, simplifying the whole process.</p><h3>Emphasizing the Benefits of XcodeGen and Addressing PBXProj Conflicts</h3><p>Using XcodeGen minimizes the risk of conflicts typically associated with Xcode’s project.pbxproj file. This file often leads to merge conflicts in version control due to its complex and verbose XML structure. By switching to XcodeGen, you can maintain clean and manageable project configurations with a more straightforward YAML or JSON approach, reducing the likelihood of such conflicts and enhancing overall project management efficiency.</p><h4>Example Workflow with XcodeGen</h4><ol><li><strong>Define the Project Specification</strong>: Create a project.yml file detailing the structure and configuration of your Xcode project.</li><li><strong>Generate the Xcode Project</strong>: Run xcodegen generate to create the Xcode project files based on the specification.</li><li><strong>Integrate with Version Control</strong>: Commit the project.yml file to version control instead of the generated .xcodeproj.</li><li><strong>Automate in CI/CD</strong>: Add a step in your CI/CD pipeline to run xcodegen generate before building and testing your project.</li></ol><h3>Demo Explanation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhICaYLX80RmlPt0DgMPLA.png" /><figcaption>TargetsTargets</figcaption></figure><p>This Xcode project structure shows a main project called “Football APP” and how it is organized into different components and targets:</p><p><strong>1. Main Project:</strong><br>- Football APP: This is the main project.</p><p><strong>2. Targets:</strong><br>- Football App: The main target for the app itself.<br>- Football APPTest: The test target for the app.</p><p><strong>3. Frameworks:</strong><br>- Design System: A framework used by the main project, providing reusable design components.<br>- Design System Target: The specific target within the Design System framework.<br>- Berita: Another framework used by the main project, possibly for news-related features.<br>- Berita Test: The test target within the Berita framework.<br>- Berita Target: The main target within the Berita framework.<br>- Berita Demo: A demo target within the Berita framework.</p><p><strong>4. Dependencies:</strong></p><p>- The main project depends on both the Design System and Berita frameworks.<br>- Each framework has its own specific targets, including test and demo targets.</p><p>we’ve implemented a modular approach for our iOS projects. Each module has its own project.yml file, managed through a central XcodegenScript.sh. This script ensures that updating the yml file is streamlined and requires minimal effort. Key steps include:</p><ol><li><strong>Creating Necessary Files</strong>: The script generates essential files like SecretFile.swift with dummy values during the setup to avoid exposing sensitive information.</li><li><strong>Defining Settings and Configurations</strong>: Project settings, targets, and configurations are defined within the project.yml file to maintain consistency across the project.</li><li><strong>Handling Different Environments</strong>: Configurations are set up correctly for different environments (Staging, Production), allowing easy switching and testing in various scenarios.</li></ol><p>Here’s a sample of what the XcodegenScript.sh might look like</p><pre>// XcodegenScript.sh<br><br>cd Football\ App<br>touch SecretFile.swift<br>echo &#39;SecretFile has been created&#39;<br><br>cd &#39;../&#39;<br>echo &#39;Back to root&#39;<br><br>cat &gt; project.yml &lt;&lt;-EOF<br>name: Football App<br>options:<br>  bundleIdPrefix: com.app.footballApp<br>  deploymentTarget:<br>    iOS: &#39;13.0&#39;<br><br>settings:<br>  base:<br>    CODE_SIGN_IDENTITY: &quot;Apple Development&quot;<br>    CODE_SIGN_STYLE: &quot;Automatic&quot;<br>    DEVELOPMENT_TEAM: &quot;XXXXXX&quot;<br>    ONLY_ACTIVE_ARCH: true<br>  Football App:<br>    SWIFT_OBJC_BRIDGING_HEADER: &quot;footballApp/helper/Header.h&quot;<br>    <br>configs:<br>  Staging: debug<br>  Production: release<br>  Production-CICD: release<br><br>configFiles:<br>  Staging: Configs/Staging.xcconfig<br>  Production: Configs/Production.xcconfig<br>  Production-CICD: Configs/Production.xcconfig<br><br>packages:<br>  ShapeUp:<br>    url: https://github.com/ryanlintott/ShapeUp<br>    from: 0.4.1<br><br>targets:<br>  Football App:<br>    type: application<br>    platform: iOS<br>    configFiles:<br>      Staging: Configs/Staging.xcconfig<br>      Production: Configs/Production.xcconfig<br>      Production-CICD: Configs/Production.xcconfig<br>    sources: <br>      - path: Football App<br>      - path: Configs/Staging.xcconfig<br>      - path: Configs/Production.xcconfig<br>      - path: PrivacyInfo.xcprivacy<br>      - path: FilterAssets<br>    resources:<br>      - path: Football App<br>      - path: Football App/resources/Assets.xcassets<br>    info:<br>      path: Football App/GoogleService-Info.plist<br>      path: Football App/Info.plist<br>      properties:<br>        BASE_URL: \$(BASE_URL)<br>        CFBundleDevelopmentRegion: \$(DEVELOPMENT_LANGUAGE)<br>        CFBundleExecutable: \$(EXECUTABLE_NAME)<br>        CFBundleIdentifier: \$(PRODUCT_BUNDLE_IDENTIFIER)<br>        CFBundleInfoDictionaryVersion: &quot;6.0&quot;<br>        CFBundleName: \$(PRODUCT_NAME)<br>        CFBundlePackageType: \$(PRODUCT_BUNDLE_PACKAGE_TYPE)<br>        FacebookAppID: &quot;XXXXX&quot;<br>        FacebookClientToken: &quot;XXXXXXX&quot;<br>        FacebookDisplayName: &quot;Football App&quot;<br>        UIAppFonts:<br>          - &quot;Lato-Regular.ttf&quot;<br>          - &quot;Lato-Italic.ttf&quot;<br>        UIStatusBarStyle: &quot;UIStatusBarStyleLightContent&quot;<br>        UISupportedInterfaceOrientations:<br>          - &quot;UIInterfaceOrientationPortrait&quot;<br>          - &quot;UIInterfaceOrientationLandscapeRight&quot;<br>        UISupportedInterfaceOrientations~ipad:<br>          - &quot;UIInterfaceOrientationPortrait&quot;<br>          - &quot;UIInterfaceOrientationPortraitUpsideDown&quot;<br>          - &quot;UIInterfaceOrientationLandscapeLeft&quot;<br>          - &quot;UIInterfaceOrientationLandscapeRight&quot;<br>        UIViewControllerBasedStatusBarAppearance: true<br>        URL_LIVE_SOCKET: \$(URL_LIVE_SOCKET)<br>        URL_SHARE_QNA: \$(URL_SHARE_QNA)<br>    settings:<br>      base:<br>        ENABLE_TESTABILITY: true<br>        MARKETING_VERSION: 2.0.1<br>        CURRENT_PROJECT_VERSION: 1<br>        SWIFT_OBJC_BRIDGING_HEADER: &quot;Football App/helper/Header.h&quot;<br>        # Script Note: For Change Asset of AppIcon<br>        ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon<br>        PRODUCT_NAME: &quot;Football&quot;<br>        TARGETED_DEVICE_FAMILY: &quot;1&quot;<br>      configs:<br>        Staging:<br>          SWIFT_ACTIVE_COMPILATION_CONDITIONS: &quot;STAGING&quot;<br>        Production:<br>          SWIFT_ACTIVE_COMPILATION_CONDITIONS: &quot;PRODUCTION&quot;<br>          DEBUG_INFORMATION_FORMAT: &quot;dwarf&quot;<br>          SWIFT_COMPILATION_MODE: &quot;incremental&quot;<br>          SWIFT_OPTIMIZATION_LEVEL: &quot;-Onone&quot;<br>          GCC_OPTIMIZATION_LEVEL: 0<br>        Production-CICD:<br>          SWIFT_ACTIVE_COMPILATION_CONDITIONS: &quot;PRODUCTIONCICD&quot;<br>          VALIDATE_PRODUCT: true<br>    entitlements:<br>      path: Football App/Football App.entitlements<br>      properties:<br>        aps-environment: &quot;development&quot;<br>        com.apple.developer.applesignin: [&quot;Default&quot;]<br>        com.apple.developer.associated-domains: [applinks:www.Football.com, applinks:eng.Footbal.com] <br>        com.apple.security.application-groups: [group.com.Football.PremierLeague]<br>    preBuildScripts:<br>      - script: |<br>                # Write Your Script In Here<br>        outputFiles:<br>          - Football/SecretFile.swift<br>        name: Generate Secret Swift File<br>      - script: |<br>                # Type a script or drag a script file from your workspace to insert its path.<br>                if which “\${PODS_ROOT}/SwiftLint/swiftlint” &gt;/dev/null; then<br>                  \${PODS_ROOT}/SwiftLint/swiftlint<br>                else<br>                  echo “warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint”<br>                fi<br>        name: Static Analysis (Linting)<br>    dependencies:<br>      - path: Libraries/DesignSystem/DesignSystem.xcodeproj<br>        framework: DesignSystem.framework<br>        implicit: true<br>      - path: Domain/DomainBerita/DomainBerita.xcodeproj<br>        framework: DomainBerita.framework<br>        embed: true<br>        implicit: true<br>      - package: ShapeUp<br><br>  Football AppTests:<br>    type: bundle.unit-test<br>    platform: iOS<br>    sources: <br>      - path: Football AppTests<br>    dependencies:<br>      - target: Football App<br>    settings:<br>      base:<br>        ENABLE_TESTABILITY: true<br>        TEST_HOST: &quot;\$(BUILT_PRODUCTS_DIR)/Football.app/Football&quot;<br>        BUNDLE_LOADER: &quot;\$(TEST_HOST)&quot;<br><br><br><br>schemes:<br>  Staging:<br>    shared: true<br>    build:<br>      targets:<br>        Football App: all<br>        Football AppTests: [test]<br>    run:<br>      config: Staging<br>      commandLineArguments:<br>        &quot;-FIRDebugEnabled&quot;: true<br>        &quot;-FIRAnalyticsDebugEnabled&quot;: true<br>    test:<br>      gatherCoverageData: true<br>      coverageTargets:<br>        - Football App<br>      targets:<br>        - name: Football AppTests<br>      config: Staging<br>      commandLineArguments:<br>        &quot;-FIRDebugEnabled&quot;: true<br>        &quot;-FIRAnalyticsDebugEnabled&quot;: true<br>    archive:<br>      config: Staging<br>      <br>  Production:<br>    shared: true<br>    build:<br>      targets:<br>        Football App: all<br>        Football AppTests: [test]<br>    run:<br>      config: Production<br>      commandLineArguments:<br>        &quot;-FIRDebugEnabled&quot;: true<br>        &quot;-FIRAnalyticsDebugEnabled&quot;: true<br>    test:<br>      gatherCoverageData: true<br>      coverageTargets:<br>        - Football App<br>      targets:<br>        - name: Football AppTests<br>      config: Production<br>      commandLineArguments:<br>        &quot;-FIRDebugEnabled&quot;: true<br>        &quot;-FIRAnalyticsDebugEnabled&quot;: true<br>    archive:<br>      config: Production<br>      <br>  Production-CICD:<br>    shared: true<br>    build:<br>      targets:<br>        Football App: all<br>        Football AppTests: [test]<br>    run:<br>      config: Production-CICD<br>      commandLineArguments:<br>        &quot;-FIRDebugEnabled&quot;: true<br>        &quot;-FIRAnalyticsDebugEnabled&quot;: true<br>    test:<br>      gatherCoverageData: true<br>      coverageTargets:<br>        - Football App<br>      targets:<br>        - name: Football AppTests<br>      config: Production-CICD<br>      commandLineArguments:<br>        &quot;-FIRDebugEnabled&quot;: true<br>        &quot;-FIRAnalyticsDebugEnabled&quot;: true<br>    archive:<br>      config: Production-CICD<br>EOF<br><br>xcodegen generate<br><br>cd &#39;./Libraries/DesignSystem&#39;<br><br>cat &gt; designSystemProject.yml &lt;&lt;-EOF<br>name: DesignSystem<br>options:<br>  bundleIdPrefix: com.app.footballApp<br>  deploymentTarget:<br>    iOS: &#39;13.0&#39;<br>settings:<br>  base:<br>    ONLY_ACTIVE_ARCH: true<br>    ENABLE_TESTABILITY: true<br>    <br>configs:<br>  Staging: debug<br>  Production: release<br>  Production-CICD: release<br><br>targets:<br>  DesignSystem:<br>    type: framework<br>    platform: iOS<br>    sources: [DesignSystem]<br>    resources: <br>      - path: DesignSystem/Info.plist<br>      - path: DesignSystem/Reusable UIs/Assets/Background.xcassets<br>      - path: DesignSystem/Reusable UIs/Assets/Icon.xcassets<br>      - path: DesignSystem/Reusable UIs/Assets/Logo.xcassets<br>      - path: DesignSystem/Reusable UIs/Assets/Image.xcassets<br>    dependencies: []<br>EOF<br><br>xcodegen generate --spec designSystemProject.yml<br><br>cat &gt; beritaFeature.yml &lt;&lt;-EOF<br>name: Berita<br>options:<br>  bundleIdPrefix: com.app.footballApp<br>  deploymentTarget:<br>    iOS: &#39;13.0&#39;<br>settings:<br>  base:<br>    ONLY_ACTIVE_ARCH: true<br>    ENABLE_TESTABILITY: true<br>    <br>configs:<br>  Staging: debug<br>  Production: release<br>  Production-CICD: release<br><br>targets:<br>  Berita:<br>    type: framework<br>    platform: iOS<br>    sources: <br>      - path: ./Demo<br>      - path: ./Source<br>    resources:<br>      - path: Source/Info.plist<br>    dependencies: <br>      - path: Libraries/DesignSystem/DesignSystem.xcodeproj<br>        framework: DesignSystem.framework<br>        embed: false<br>        implicit: true<br>  <br>  BeritaTests:<br>    type: bundle.unit-test<br>    platform: iOS<br>    sources: [UnitTests]<br>    dependencies:<br>      - path: Features/Berita/Berita.xcodeproj<br>        framework: Berita.framework<br>        embed: false<br>        implicit: true<br>    settings:<br>      base:<br>        FRAMEWORK_SEARCH_PATHS: &quot;./Developer/Library/Frameworks&quot;<br>        LIBRARY_SEARCH_PATHS: &quot;./Developer/usr/lib&quot;<br>  <br>  Berita-Demo:<br>    type: application<br>    platform: iOS<br>    sources: [Demo]<br>    dependencies:<br>      - target: Berita<br>        embed: true<br>    settings:<br>      base:<br>        FRAMEWORK_SEARCH_PATHS: &quot;./Developer/Library/Frameworks&quot;<br>        LIBRARY_SEARCH_PATHS: &quot;./Developer/usr/lib&quot;<br>EOF<br><br>xcodegen generate --spec beritaFeature.yml<br><br>cd &#39;../../&#39;<br>pod install</pre><h3>Explanation</h3><h4>Creating default Value</h4><pre>cd Football\ App<br>touch SecretFile.swift<br>echo &#39;SecretFile has been created&#39;<br><br>cd &#39;../&#39;<br>echo &#39;Back to root&#39;</pre><p>This is done to provide a default file for files that are not included in GitHub or files that are generated during the build script. If a default file is not provided, it will cause an error during xcodegen generate because the reference file does not exist.</p><p><strong>Notes:</strong> If there are files needed by the app but are confidential and not included in GitHub, it is mandatory to create a blank default file so that it can be detected by xcodegen.</p><p><strong>Project Define</strong></p><pre>name: Football App<br>options:<br>  bundleIdPrefix: com.app.footballApp<br>  deploymentTarget:<br>    iOS: &#39;13.0&#39;</pre><p>This is the initial code where we define the project name and the deployment target. A single project can have multiple targets, which we will define below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8V77Aamf0n2eej7mtztPAg.png" /></figure><p>The Project Football App has two targets:</p><ol><li><strong>Football App</strong></li><li><strong>Football AppTests</strong></li></ol><h4>Setting Build Setting</h4><pre>settings:<br>  base:<br>    CODE_SIGN_IDENTITY: &quot;Apple Development&quot;<br>    CODE_SIGN_STYLE: &quot;Automatic&quot;<br>    DEVELOPMENT_TEAM: &quot;XXXXXX&quot;<br>    ONLY_ACTIVE_ARCH: true<br>  Football App:<br>    SWIFT_OBJC_BRIDGING_HEADER: &quot;footballApp/helper/Header.h&quot;</pre><ul><li><strong>Base Settings:</strong> These settings are applied globally to all targets in the project.</li><li><strong>Football App Target:</strong> The settings specific to the Football App target are defined under the targets section.</li></ul><p>In XcodeGen, build settings are often structured with base settings and then extended or overridden at the target level as needed. Make sure to verify with the <a href="https://xcodegen.app/">XcodeGen documentation</a> for the latest and most accurate details.</p><h4>Configs and ConfigFiles</h4><pre>configs:<br>  Staging: debug<br>  Production: release<br>  Production-CICD: release<br><br>configFiles:<br>  Staging: Configs/Staging.xcconfig<br>  Production: Configs/Production.xcconfig<br>  Production-CICD: Configs/Production.xcconfig</pre><p>Kita memiliki 3 schema, yakni Staging, Production, Production-CICD dimana</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXPVNkRhF13JxK3onqQiDw.png" /></figure><p>We have three schemes: Staging, Production, and Production-CICD.</p><p><strong>Configs:</strong></p><ul><li>Defines the build configuration for each scheme.</li><li>Staging, Production, and Production-CICD are set to debug or release.</li><li>Values must be either debug or release to apply the default build settings.</li></ul><p><strong>ConfigFiles:</strong></p><ul><li>Associates each scheme with a specific .xcconfig file.</li><li>These files manage settings like secret keys and API URLs.</li><li>Each scheme (Staging, Production, Production-CICD) should have its own .xcconfig file.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*WdYoyB2qzAOTgDZ9d8r9Cw.png" /></figure><p><strong>SPM Packages</strong></p><p>To define an SPM package dependency in your XcodeGen configuration, use the following format:</p><pre>packages:<br>  ShapeUp:<br>    url: https://github.com/ryanlintott/ShapeUp<br>    from: 0.4.1</pre><p><strong>Explanation:</strong></p><ul><li><strong>packages:</strong>: This section lists all Swift Package Manager (SPM) packages your project depends on.</li><li><strong>ShapeUp:</strong>: The name of the package.</li><li><strong>url:</strong>: The URL of the package repository.</li><li><strong>from:</strong>: Specifies the minimum version of the package that should be used.</li></ul><p><strong>Target Football App di project Football App</strong></p><p>Here’s how to define the Football App target in your XcodeGen project:</p><pre>targets:<br>  Football App:<br>    type: application<br>    platform: iOS<br>    configFiles:<br>      Staging: Configs/Staging.xcconfig<br>      Production: Configs/Production.xcconfig<br>      Production-CICD: Configs/Production.xcconfig<br>    sources: <br>      - path: Football App<br>      - path: Configs/Staging.xcconfig<br>      - path: Configs/Production.xcconfig<br>      - path: FilterAssets<br>    resources:<br>      - path: Football App<br>      - path: Football App/resources/Assets.xcassets</pre><p><strong>Explanation:</strong></p><ul><li><strong>targets:</strong>: Defines the various targets within your project. In this case, it&#39;s the Football App target.</li><li><strong>type:</strong>: Specifies the type of target. Here, it&#39;s an application.</li><li><strong>platform:</strong>: Sets the platform for the target. Here, it&#39;s iOS.</li><li><strong>configFiles:</strong>: Associates each build configuration (Staging, Production, Production-CICD) with a specific .xcconfig file. These files contain configuration settings for different build environments.</li><li><strong>sources:</strong>: Lists the source files and directories for the target. You can specify directories or files needed for the application. XcodeGen will appropriately parse source files, resources, headers, and .lproj files.</li><li><strong>resources:</strong>: Lists the resources included in the target. Typically includes asset catalogs and other resources needed by the application.</li></ul><p><strong>Setting Info Plist:</strong></p><p>To define the Info.plist settings in your XcodeGen configuration, use the following format:</p><pre>info:<br>      path: Football App/GoogleService-Info.plist<br>      path: Football App/Info.plist<br>      properties:<br>        BASE_URL: \$(BASE_URL)<br>        CFBundleDevelopmentRegion: \$(DEVELOPMENT_LANGUAGE)<br>        CFBundleExecutable: \$(EXECUTABLE_NAME)<br>        CFBundleIdentifier: \$(PRODUCT_BUNDLE_IDENTIFIER)<br>        CFBundleInfoDictionaryVersion: &quot;6.0&quot;<br>        CFBundleName: \$(PRODUCT_NAME)<br>        CFBundlePackageType: \$(PRODUCT_BUNDLE_PACKAGE_TYPE)<br>        FacebookAppID: &quot;XXXXX&quot;<br>        FacebookClientToken: &quot;XXXXXXX&quot;<br>        FacebookDisplayName: &quot;Football App&quot;<br>        UIAppFonts:<br>          - &quot;Lato-Regular.ttf&quot;<br>          - &quot;Lato-Italic.ttf&quot;<br>        UIStatusBarStyle: &quot;UIStatusBarStyleLightContent&quot;<br>        UISupportedInterfaceOrientations:<br>          - &quot;UIInterfaceOrientationPortrait&quot;<br>          - &quot;UIInterfaceOrientationLandscapeRight&quot;<br>        UISupportedInterfaceOrientations~ipad:<br>          - &quot;UIInterfaceOrientationPortrait&quot;<br>          - &quot;UIInterfaceOrientationPortraitUpsideDown&quot;<br>          - &quot;UIInterfaceOrientationLandscapeLeft&quot;<br>          - &quot;UIInterfaceOrientationLandscapeRight&quot;<br>        UIViewControllerBasedStatusBarAppearance: true<br>        URL_LIVE_SOCKET: \$(URL_LIVE_SOCKET)<br>        URL_SHARE_QNA: \$(URL_SHARE_QNA)</pre><p>Defining Info.plist settings in XcodeGen is crucial because every time XcodeGen generates the project, the plist file will be recreated from scratch. If not defined, custom settings would be lost.</p><p><strong>Setting Per Target</strong></p><pre>settings:<br>      base:<br>        ENABLE_TESTABILITY: true<br>        MARKETING_VERSION: 2.0.1<br>        CURRENT_PROJECT_VERSION: 1<br>        SWIFT_OBJC_BRIDGING_HEADER: &quot;Football App/helper/Header.h&quot;<br>        # Script Note: For Change Asset of AppIcon<br>        ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon<br>        PRODUCT_NAME: &quot;Football&quot;<br>        TARGETED_DEVICE_FAMILY: &quot;1&quot;<br>      configs:<br>        Staging:<br>          SWIFT_ACTIVE_COMPILATION_CONDITIONS: &quot;STAGING&quot;<br>        Production:<br>          SWIFT_ACTIVE_COMPILATION_CONDITIONS: &quot;PRODUCTION&quot;<br>          DEBUG_INFORMATION_FORMAT: &quot;dwarf&quot;<br>          SWIFT_COMPILATION_MODE: &quot;incremental&quot;<br>          SWIFT_OPTIMIZATION_LEVEL: &quot;-Onone&quot;<br>          GCC_OPTIMIZATION_LEVEL: 0<br>        Production-CICD:<br>          SWIFT_ACTIVE_COMPILATION_CONDITIONS: &quot;PRODUCTIONCICD&quot;<br>          VALIDATE_PRODUCT: true</pre><p>In the base settings of a project, we define several settings that will apply to all targets. However, if we want to specify settings for a particular target, we can define them separately for each target.</p><p><strong>Explanation:</strong></p><p>Settings in XcodeGen correspond to the “Build Settings” tab in Xcode. They include:</p><ul><li><strong>base:</strong> - Default settings that apply to all configurations and targets. Use this to set global defaults for all configurations.</li><li><strong>configs:</strong> - Specific settings for different configurations. This maps configuration names (e.g., Staging, Production) to particular settings. These settings will override the base settings for the specified configurations. For example, settings under Staging will apply to all configurations that include the Staging keyword, such as Staging Debug or Staging Release. However, settings with an exact match (e.g., Release) will only apply to that specific configuration and not to others like Staging Release.</li><li><strong>groups:</strong> - List of setting groups to include and merge. This allows for including and merging settings from predefined groups, which helps in organizing and reusing settings across different targets or configurations.</li></ul><p>In summary:</p><ul><li><strong>base:</strong>: Applies default settings to all configurations and targets.</li><li><strong>configs:</strong>: Allows specifying settings for particular configurations.</li><li><strong>groups:</strong>: Facilitates including and merging settings from groups.</li></ul><p>To apply settings across the entire project, use base. For settings specific to certain configurations, use configs.</p><p><strong>Contoh:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SK_k8_JXtaDK-suzjHDIGQ.png" /></figure><p>In Build Settings → Framework Search Paths, we need to configure paths for each configuration. This can be handled using the configs section in XcodeGen.</p><p><strong>Setting Entitlements</strong></p><p>To configure entitlements in XcodeGen, you need to specify the path to the entitlements file and define the necessary properties. Here’s how you can set it up:</p><pre>entitlements:<br>      path: Football App/Football App.entitlements<br>      properties:<br>        aps-environment: &quot;development&quot;<br>        com.apple.developer.applesignin: [&quot;Default&quot;]<br>        com.apple.developer.associated-domains: [applinks:www.Football.com, applinks:eng.Footbal.com] <br>        com.apple.security.application-groups: [group.com.Football.PremierLeague]</pre><p><strong>Explanation:</strong></p><ul><li><strong>path:</strong>: Specifies the location of the entitlements file within your project directory.</li><li><strong>properties:</strong>: Defines the entitlements properties that you need:</li><li><strong>aps-environment:</strong>: Configures the push notification environment (e.g., development or production).</li><li><strong>com.apple.developer.applesignin:</strong>: Specifies Apple Sign-In capabilities.</li><li><strong>com.apple.developer.associated-domains:</strong>: Lists the associated domains for universal links.</li><li><strong>com.apple.security.application-groups:</strong>: Defines application groups for data sharing between apps.</li></ul><p>If your project requires specific entitlements, ensure to create the appropriate entitlements file and set these properties accordingly. This setup is crucial for functionalities like associated domains, app groups, and push notifications.</p><p><strong>Custom Prebuild Script</strong></p><p>In XcodeGen, you can define custom prebuild scripts to run specific tasks before the build process starts. This is especially useful for tasks such as generating files or performing static analysis. Here’s how you can configure prebuild scripts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-MXKBXcAohhfchJyU1hrzw.png" /></figure><pre>preBuildScripts:<br>      - script: |<br>                # Write Your Script In Here<br>        outputFiles:<br>          - Football/SecretFile.swift<br>        name: Generate Secret Swift File<br>      - script: |<br>                # Type a script or drag a script file from your workspace to insert its path.<br>                if which “\${PODS_ROOT}/SwiftLint/swiftlint” &gt;/dev/null; then<br>                  \${PODS_ROOT}/SwiftLint/swiftlint<br>                else<br>                  echo “warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint”<br>                fi<br>        name: Static Analysis (Linting)</pre><p><strong>Explanation:</strong></p><ul><li><strong>preBuildScripts:</strong>: This section allows you to specify custom scripts that run before the build process.</li><li><strong>script:</strong>: The actual shell script to be executed. This can include any commands needed for your prebuild process.</li><li><strong>outputFiles:</strong>: Lists files that will be created or modified by the script. This helps Xcode understand the files generated by the script, which is important for keeping track of build artifacts.</li><li><strong>name:</strong>: A descriptive name for the script, which helps in identifying it in the build phases.</li></ul><p><strong>Examples:</strong></p><p><strong>Generate Secret Swift File:</strong></p><ul><li>This script generates or updates SecretFile.swift used in the project. You would add your own commands to create or modify the file as needed.</li></ul><p><strong>Static Analysis (Linting):</strong></p><ul><li>This script runs SwiftLint to check for code style issues. It first checks if SwiftLint is installed, and if so, executes it. If not, it prints a warning message.</li></ul><p><strong>Usage Notes:</strong></p><ul><li>When xcodegen generates the project, it will recreate the entire project structure, including any custom scripts. Therefore, it’s essential to include these scripts in your xcodegen configuration so they are re-applied after each generation.</li><li>Custom scripts are executed during the build process, ensuring that tasks such as file generation or code linting are handled automatically before the build starts.</li></ul><p><strong>Dependencies</strong></p><p>In XcodeGen, you define project dependencies to ensure that your project links with other frameworks or packages. Dependencies must be configured in the dependencies section. Here’s how you can set it up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHwgdKyOSbmtbvWu8g3iww.png" /></figure><pre>dependencies:<br>      - path: Libraries/DesignSystem/DesignSystem.xcodeproj<br>        framework: DesignSystem.framework<br>        implicit: true<br>      - path: Domain/DomainBerita/DomainBerita.xcodeproj<br>        framework: DomainBerita.framework<br>        embed: true<br>        implicit: true<br>      - package: ShapeUp</pre><p><strong>path:</strong>: Specifies the path to the Xcode project file that contains the dependency.</p><p><strong>framework:</strong>: The name of the framework to be linked.</p><p><strong>implicit:</strong>: If true, Xcode will automatically link the dependency without needing explicit inclusion in the target. Default is false.</p><p><strong>embed:</strong>: If true, the framework will be embedded in the app bundle. Use this for frameworks that need to be included with the app, such as those containing resources. Default is false.</p><p><strong>package:</strong>: Refers to an external Swift package managed by Swift Package Manager (SPM). Specify the package name as defined in your Package.swift file.</p><p>Ensure all dependencies used in your project are included in this list. If you add new dependencies, remember to update this section to reflect those changes. This ensures that XcodeGen correctly configures your project with all necessary dependencies.</p><p><strong>Another Target di Football App Project</strong></p><p>For setting up a test target in XcodeGen, you’ll need to define the target, specify the sources, dependencies, and configure settings appropriately. Here’s how you can configure a unit test target for Football AppTests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*au-OkA8n4QaQxKoCvEdtng.png" /></figure><pre>Football AppTests:<br>    type: bundle.unit-test<br>    platform: iOS<br>    sources: <br>      - path: Football AppTests<br>    dependencies:<br>      - target: Football App<br>    settings:<br>      base:<br>        ENABLE_TESTABILITY: true<br>        TEST_HOST: &quot;\$(BUILT_PRODUCTS_DIR)/Football.app/Football&quot;<br>        BUNDLE_LOADER: &quot;\$(TEST_HOST)&quot;</pre><p><strong>Key Points:</strong></p><ul><li><strong>type: bundle.unit-test</strong>: Defines the target as a unit test bundle.</li><li><strong>sources:</strong>: Path to your test files.</li><li><strong>dependencies:</strong>: List of targets this test target depends on (e.g., Football App).</li><li><strong>settings:</strong>:</li><li><strong>ENABLE_TESTABILITY: true</strong>: Enables testability.</li><li><strong>TEST_HOST:</strong>: Path to the test host app.</li><li><strong>BUNDLE_LOADER:</strong>: Path to the bundle being tested.</li></ul><p>This configuration includes your test sources, sets dependencies, and applies necessary settings.</p><p><strong>Schema</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRVAN_iA-79nMpsCBcbACQ.png" /></figure><pre>schemes:<br>  Staging:<br>    shared: true<br>    build:<br>      targets:<br>        Football App: all<br>        Football AppTests: [test]<br>    run:<br>      config: Staging<br>      commandLineArguments:<br>        &quot;-FIRDebugEnabled&quot;: true<br>        &quot;-FIRAnalyticsDebugEnabled&quot;: true<br>    test:<br>      gatherCoverageData: true<br>      coverageTargets:<br>        - Football App<br>      targets:<br>        - name: Football AppTests<br>      config: Staging<br>      commandLineArguments:<br>        &quot;-FIRDebugEnabled&quot;: true<br>        &quot;-FIRAnalyticsDebugEnabled&quot;: true<br>    archive:<br>      config: Staging<br>      <br>  Production:<br>    shared: true<br>    build:<br>      targets:<br>        Football App: all<br>        Football AppTests: [test]<br>    run:<br>      config: Production<br>      commandLineArguments:<br>        &quot;-FIRDebugEnabled&quot;: true<br>        &quot;-FIRAnalyticsDebugEnabled&quot;: true<br>    test:<br>      gatherCoverageData: true<br>      coverageTargets:<br>        - Football App<br>      targets:<br>        - name: Football AppTests<br>      config: Production<br>      commandLineArguments:<br>        &quot;-FIRDebugEnabled&quot;: true<br>        &quot;-FIRAnalyticsDebugEnabled&quot;: true<br>    archive:<br>      config: Production</pre><p>A scheme in Xcode defines a collection of settings and configurations for building, running, testing, profiling, and archiving your app. Using xcodegen, you can automate the creation of these schemes in a YAML file.</p><h4>Key Sections in a Scheme</h4><ol><li><strong>Shared</strong>: Indicates if the scheme is shared among all users of the project.</li><li><strong>Build</strong>: Specifies the targets to be built. Each target can have different build actions (e.g., all, test).</li><li><strong>Run</strong>: Defines the configuration and command-line arguments used when running the app.</li><li><strong>Test</strong>: Specifies settings for running tests, including whether to gather coverage data and which targets to include.</li><li><strong>Archive</strong>: Defines the configuration to be used when archiving the app for distribution.</li></ol><h4>Example Breakdown</h4><ul><li>shared: true: The scheme is shared.</li><li>build: Builds Football App (all parts) and Football AppTests (only for testing).</li><li>run: Uses the Staging configuration and sets Firebase debugging arguments.</li><li>test: Gathers code coverage data for Football App and runs Football AppTests with the Stagingconfiguration.</li><li>archive: Uses the Staging configuration for archiving.</li><li>“-FIRDebugEnabled”: true: This enables Firebase debug mode, These arguments are passed to the app when it is run under the MyScheme scheme with the Debug configuration, modifying the app&#39;s behavior without altering the source code.</li></ul><h4>Framework &amp; Other Features</h4><h4>Design System</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*pJGYPbQD-yTTkW0ykH5YGQ.png" /></figure><p>Once you’ve set up the main project, such as Football App, you need to define additional frameworks, like Berita and DesignSystem. Here’s how to do it:</p><pre>cd &#39;./Libraries/DesignSystem&#39;<br><br>cat &gt; designSystemProject.yml &lt;&lt;-EOF<br>name: DesignSystem<br>options:<br>  bundleIdPrefix: com.app.footballApp<br>  deploymentTarget:<br>    iOS: &#39;13.0&#39;<br>settings:<br>  base:<br>    ONLY_ACTIVE_ARCH: true<br>    ENABLE_TESTABILITY: true<br>    <br>configs:<br>  Staging: debug<br>  Production: release<br>  Production-CICD: release<br><br>targets:<br>  DesignSystem:<br>    type: framework<br>    platform: iOS<br>    sources: [DesignSystem]<br>    resources: <br>      - path: DesignSystem/Info.plist<br>      - path: DesignSystem/Reusable UIs/Assets/Background.xcassets<br>      - path: DesignSystem/Reusable UIs/Assets/Icon.xcassets<br>      - path: DesignSystem/Reusable UIs/Assets/Logo.xcassets<br>      - path: DesignSystem/Reusable UIs/Assets/Image.xcassets<br>    dependencies: []<br>EOF<br><br>xcodegen generate --spec designSystemProject.yml</pre><p><strong>Key Points:</strong></p><ul><li><strong>UI-Only Module</strong>: The DesignSystem module focuses on UI components and does not include unit tests.</li><li><strong>Resource Allocation</strong>: Unlike the main Football App, where resources are automatically included, DesignSystemrequires explicit resource paths for assets.</li></ul><p>This configuration ensures that the DesignSystem module is correctly set up with all necessary resources and settings.</p><h4>Berita</h4><pre>cat &gt; beritaFeature.yml &lt;&lt;-EOF<br>name: Berita<br>options:<br>  bundleIdPrefix: com.app.footballApp<br>  deploymentTarget:<br>    iOS: &#39;13.0&#39;<br>settings:<br>  base:<br>    ONLY_ACTIVE_ARCH: true<br>    ENABLE_TESTABILITY: true<br>    <br>configs:<br>  Staging: debug<br>  Production: release<br>  Production-CICD: release<br><br>targets:<br>  Berita:<br>    type: framework<br>    platform: iOS<br>    sources: <br>      - path: ./Demo<br>      - path: ./Source<br>    resources:<br>      - path: Source/Info.plist<br>    dependencies: <br>      - path: Libraries/DesignSystem/DesignSystem.xcodeproj<br>        framework: DesignSystem.framework<br>        embed: false<br>        implicit: true<br>  <br>  BeritaTests:<br>    type: bundle.unit-test<br>    platform: iOS<br>    sources: [UnitTests]<br>    dependencies:<br>      - path: Features/Berita/Berita.xcodeproj<br>        framework: Berita.framework<br>        embed: false<br>        implicit: true<br>    settings:<br>      base:<br>        FRAMEWORK_SEARCH_PATHS: &quot;./Developer/Library/Frameworks&quot;<br>        LIBRARY_SEARCH_PATHS: &quot;./Developer/usr/lib&quot;<br>  <br>  Berita-Demo:<br>    type: application<br>    platform: iOS<br>    sources: [Demo]<br>    dependencies:<br>      - target: Berita<br>        embed: true<br>    settings:<br>      base:<br>        FRAMEWORK_SEARCH_PATHS: &quot;./Developer/Library/Frameworks&quot;<br>        LIBRARY_SEARCH_PATHS: &quot;./Developer/usr/lib&quot;<br>EOF</pre><p>From the Football App project, we also have a dependency on another framework, which is Berita. Berita has three targets: Berita, Berita-Demo, and BeritaTests. Essentially, the implementation is similar to the main target where we need to define dependencies and some build settings. Adjust the settings according to your actual project.</p><h3>Tips and Tricks</h3><p>Always maintain 2 project folders: one for working with XcodeGen and the other for comparison. Use the second folder as a reference for creating your XcodeGen scripts.</p><p><strong>Closing</strong></p><p>Special thanks to Arnold Pangestu and Rio Rizky for their tireless work over two sleepless weeks transforming IDN from modular Xcode project to use Xcodegen</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a45f750b7770" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/goodbye-pbxproj-conflicts-simplify-your-ios-project-management-with-xcodegen-a45f750b7770">Goodbye pbxproj Conflicts: Simplify Your iOS Project with XcodeGen</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Sail to SwiftUI with IDN App: A Seamless Transition Experience]]></title>
            <link>https://engineering.idn.media/setting-sail-to-swiftui-with-idn-app-a-seamless-transition-experience-87437b3e6990?source=rss-1cd75752f934------2</link>
            <guid isPermaLink="false">https://medium.com/p/87437b3e6990</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[visionos]]></category>
            <dc:creator><![CDATA[Bevan christian]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 11:51:59 GMT</pubDate>
            <atom:updated>2024-01-30T11:51:59.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IeQDa2pB7c3uYouL0KhKCA.png" /></figure><p>In our journey of migrating from UIKit to SwiftUI at the iOS IDN App, we follow a structured process. It begins with preparing our team, as we delve into a new framework and syntax for UI creation. While we have developers with SwiftUI experience, a quick refresher is essential, given the time gap since their last SwiftUI use.</p><p>Next, we prepare basic components like AsyncImage and other custom elements.</p><p>The third step involves a gradual shift of tableview cell and UIKit components to SwiftUI.</p><p>Finally, we take the plunge by migrating entire pages to SwiftUI, starting with simpler ones to ease the transition.</p><p>As expected, challenges arise during this process, such as navigation issues and connecting UIKit with SwiftUI. Since our app has a minimum iOS 13 requirement, many SwiftUI features aren’t available, leading to manual creation of components like loading indicators and LazyVStack.</p><p>Post resolving issues, we ensure the app meets standards. Performance concerns, especially on iOS 13, necessitate specific handling. For instance, we can’t use LazyVStack for iOS 13, so we adapt by using a regular list.</p><p>To exemplify, consider our approach to solving performance issues on iOS 13:</p><pre>  // Code snippet illustrating compromise for sticky tab in iOS 13<br>if #available(iOS 14.0, *) {<br>    ScrollView(.vertical, showsIndicators: false) {<br>        // SwiftUI layout for iOS 14 with sticky tab<br>        // ...<br>    }.background(<br>        ScrollDetector { offset in<br>            viewModel.offsetY = -offset<br>        } onDraggingEnd: { _, _ in }<br>    )<br>} else {<br>    List {<br>        // SwiftUI layout for iOS 13 without sticky tab<br>        // ...<br>    }<br>    .onAppear {<br>        if reachBottom == false {<br>            reachBottom = true<br>        }<br>    }<br>}</pre><p>In addressing product requirements, our approach involves utilizing a list in iOS 13 and a ScrollView in iOS 14. This choice stems from the need to track offsets, ensuring our tab bar remains fixed at the top. Notably, we observe adjustments like list row insets and padding modifications to align with our UI, as the default list in iOS 13 comes with inherent padding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*T_wDu8X6sVCEqC8rH1fMIw.png" /></figure><p>However, a notable challenge arises when dealing with the potential sluggishness of ScrollView, ForEach, and VStack. To counteract this, we embrace ScrollView, ForEach, and LazyVStack for iOS 14. Conversely, for iOS 13, we lean towards a list and section approach. During discussions with the product team, a strategic decision was made to forego making the tab sticky for iOS 13. The rationale behind this choice lies in the limitations of obtaining offsets within a list, ultimately prioritizing performance through the use of a list.</p><p>For those embarking on the migration journey to SwiftUI from UIKit, with a minimum user version set to 13, it’s imperative to consider and make compromises for the sake of optimal performance.</p><h4><strong>Conclusion</strong></h4><p>Currently, our team is in the midst of a lengthy process to transition all code to SwiftUI. However, due to the limitations imposed by the minimum requirement of iOS 13, we are taking a conservative approach in selecting which layouts to migrate. This decision is made with the consideration of not disrupting the functionality that is already in place and running smoothly.</p><p>The primary reason behind our shift to SwiftUI is to enable better code maintenance and faster development in the future. With the adoption of SwiftUI, we anticipate that the code maintenance process will become more efficient, and application development will be more responsive to evolving requirements. Speed and development excellence are the primary focus of this initiative, ensuring that our software evolves in line with the latest standards.</p><p>In next article i will publish how we wrap UIKit code to SwiftUI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87437b3e6990" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/setting-sail-to-swiftui-with-idn-app-a-seamless-transition-experience-87437b3e6990">Setting Sail to SwiftUI with IDN App: A Seamless Transition Experience</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift UITableView Prefetching: A Guide to Smoother Scrolling (Part 2)]]></title>
            <link>https://engineering.idn.media/swift-uitableview-prefetching-a-guide-to-smoother-scrolling-part-2-bbef7c579a44?source=rss-1cd75752f934------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbef7c579a44</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[table-view-controller]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bevan christian]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 12:22:12 GMT</pubDate>
            <atom:updated>2023-11-22T12:22:12.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8n07sytcUxckn3D3" /><figcaption>Photo by <a href="https://unsplash.com/@martenbjork?utm_source=medium&amp;utm_medium=referral">Marten Bjork</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the previous article, I provided information about prefetching in a TableView. Prefetching essentially performs operations such as downloading images, data, and loading assets ahead of time for the next 5–10 cells (depending on the TableView settings). Unlike the usual practice of downloading and loading images in the cellForRowAt method, prefetching occurs much earlier, even before viewWillAppear. This gives your cells more time to download images, assets, or data, ensuring that they are ready when the user scrolls to those cells.</p><p>Despite the significance of prefetching, there is limited discussion about it in the articles out there, especially when dealing with complex cells. Have you ever encountered a scenario where a TableView contains more than one type of cell, and each cell has the responsibility to download images or assets?</p><p>If so, this article is tailored for you. I will delve into prefetching for complex TableViews. However, if you haven’t read the first part of the article, I recommend doing so before proceeding.</p><p><a href="https://medium.com/idn-engineering/swift-uitableview-prefetching-a-guide-to-smoother-scrolling-a12251e2e774">Swift UITableView Prefetching: A Guide to Smoother Scrolling</a></p><h3>Screnario</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*RnzuMmBbiP5q0SI4PPqygg.png" /></figure><p>You have a TableView with a filter button. When the filter button is pressed, the layout changes slightly to display three types of cells: headlineCell, feedCell, and adsCell. However, you only want to prefetch data for one type of cell, which is feedCell. You do not want to prefetch data for headlineCell and adsCell.</p><p>To address this, the first step is to make adjustments in the prefetchRowsAt method. Typically, prefetching is done for the FeedCell, and the code for this would look like the following:</p><h3>Solution 1</h3><pre>func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {<br>        for indexPath in indexPaths {<br>            if let cell = tableView.cellForRow(at: indexPath) as? FeedCell {<br>                  prefetchFeedCell(at: indexPath, data: latestData?[indexPath.row])<br>             }<br>        }<br>  }</pre><p>The provided Swift code attempts to implement data prefetching for a UITableView using the tableView(_:prefetchRowsAt:) method. However, a crucial issue arises when trying to prefetch data for cells of type FeedCell. The challenge stems from the fact that, during prefetching, the cell at index `x` might still be a different type, such as headlineCell or addCell.</p><p>In the TableView cell system, cells are dequeued, meaning that at a given index, the cell might not yet be a FeedCell. For instance, at index 20, the cell could still be a headlineCell or another type. Consequently, the prefetching mechanism fails to work smoothly because the condition to prefetch data into a FeedCell isn’t fulfilled.</p><p>To address this, it’s essential to reconsider the prefetching strategy. The current logic may need adjustments to account for the dynamic nature of cell dequeuing in a TableView. This might involve refining the prefetching conditions to consider multiple cell types or exploring alternative approaches to ensure reliable data prefetching for `FeedCell`.</p><h3>Better Solution</h3><p>Therefore the solution is to immediately prefetch all the data but check the data whether the data is in accordance with FeedCell or not, if the data is headline data or another data beside Feed then we can just ignore it.</p><pre> func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {<br>        for indexPath in indexPaths {<br>            switch filterType {<br>            case .trending:<br>                if let latest = latestData, indexPaths.row &lt; latestData.count {<br>                    prefetchFeedCell(at: indexPath, data: latest[indexPath.row])<br>                }<br>            case .other:<br>                 if let othersData = otherData, indexPath.row &lt; otherData.count {<br>                     prefetchFeedCell(at: indexPath, data: othersData[indexPath.row])<br>                 }  <br>            case .empty:<br>                continue<br>            }<br>        }<br>    }<br><br><br> private func prefetchFeedCell(at indexPath: IndexPath, data: Any) {<br>        guard let viewData = data as? FeedData else {<br>            // Handle the case where the data is not of type Berita<br>            return<br>        }<br>        let dataLoader = ImageLoadOperation(viewData.cover?.sourceUrl)<br>        operationQueue.addOperation(dataLoader)<br>        operationCell[indexPath] = dataLoader<br> }</pre><p>for cell for willDisplay there is no change</p><pre>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {<br>    // Checking if the cell is of type ListArticleSmall and presenter&#39;s viewData is available<br>    if let cell = cell as? FeedCell {<br>        <br>        // Closure for updating the cell&#39;s image when the download process is complete<br>        let updateCellClosure: (UIImage?) -&gt; () = { [weak self] image in<br>            guard let self = self else { return }<br>            <br>            // Configuring the cell when the download is complete<br>            operationCell.removeValue(forKey: indexPath)<br>            cell.setImageDirectly(image: image)<br>        }<br>        <br>        // Checking if there is an ongoing prefetch process for this index<br>        if let dataLoader = operationCell[indexPath] {<br>            <br>            if let image = dataLoader.image {<br>                // If there is an image, assign it directly to the cell<br>               <br>                operationCell.removeValue(forKey: indexPath)<br>                cell.setImageDirectly(image: image)<br>            } else {<br>                // If there is no image yet, assign the updateClosure<br>                // so that when the image is ready, it can be assigned to the cell<br>                dataLoader.loadingCompleteHandler = updateCellClosure<br>            }<br>        } else {<br>            // If prefetch process has not occurred, initiate the prefetch<br>            // and assign it to the completion handler for direct assignment when the image is ready<br>            if operationCell[indexPath] == nil {<br>                let dataLoader = DataLoadOperation(viewData[indexPath.row].coverSourceUrl)<br>                dataLoader.loadingCompleteHandler = updateCellClosure<br>                operationQueue.addOperation(dataLoader)<br>                operationCell[indexPath] = dataLoader<br>            }<br>        }<br>      cell.configureCell(model: viewData[indexPath.row])<br>    } else if let headlineCell = cell as? HeadlineCell {<br>      // Do nothing because still use cell for row at<br>    }<br>}</pre><h3>Summary</h3><p>When implementing prefetching in a TableView, it’s crucial to maintain awareness of TableView basics, particularly cell dequeuing. In the prefetchRowsAt function, it&#39;s essential to directly check the data type, ensuring that the fundamentals of TableView, such as cell dequeueing, are not overlooked.</p><h3>Additional Considerations</h3><p>It’s worth noting that the cancelPrefetch and didEndDisplay functions may not require changes. However, it&#39;s important to remain vigilant about these aspects to ensure a comprehensive and smooth implementation of prefetching.</p><h3>Key Takeaway</h3><p>Prefetching involves not only optimizing the process but also adapting it to the dynamic nature of TableView cells. By incorporating checks for data types directly into the prefetching logic, we can seamlessly integrate prefetching functionality while adhering to TableView fundamentals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbef7c579a44" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/swift-uitableview-prefetching-a-guide-to-smoother-scrolling-part-2-bbef7c579a44">Swift UITableView Prefetching: A Guide to Smoother Scrolling (Part 2)</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift UITableView Prefetching: A Guide to Smoother Scrolling]]></title>
            <link>https://engineering.idn.media/swift-uitableview-prefetching-a-guide-to-smoother-scrolling-a12251e2e774?source=rss-1cd75752f934------2</link>
            <guid isPermaLink="false">https://medium.com/p/a12251e2e774</guid>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[table-view-controller]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Bevan christian]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 03:04:40 GMT</pubDate>
            <atom:updated>2023-11-20T03:04:40.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*66V6WPsQKLQ9bE2S" /><figcaption>Photo by <a href="https://unsplash.com/@mike_van_den_bos?utm_source=medium&amp;utm_medium=referral">Mike van den Bos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When developing a UICollectionView or UITableView, the conventional approach involves downloading images within the cellForRow method. However, this method can adversely affect user experience, especially as cells are scrolled. The simultaneous execution of displaying cells and downloading images can lead to a decrease in frame rate, as stipulated by Apple, resulting in slower image loading, particularly when downloads commence only upon cell visibility.</p><p>To tackle this challenge, iOS offers a built-in solution called prefetching. By setting the prefetchDataSource of your table or collection view to a delegate, usually implemented by the view controller, and conforming to its protocol, you can significantly enhance the performance of image loading.</p><p>Here’s an illustration of implementing prefetching for a UITableView:</p><p><strong>Set PrefetchDataSource</strong></p><pre>class YourTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, UITableViewDataSourcePrefetching {<br><br>    var operationCell: [IndexPath: DataLoadOperation] = [:]<br>    let operationQueue: OperationQueue = {<br>        let operation = OperationQueue()<br>        return operation<br>    }()<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        // Set the prefetching data source<br>        tableView.prefetchDataSource = self<br>    }<br>    <br>    // Implement UITableViewDataSourcePrefetching method<br>    func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {<br>        // Perform image downloading for the indexPaths<br>        // This is where you initiate the image downloads in advance<br>    }<br>    <br>    // Other UITableViewDataSource methods...<br>    <br>    // Other UITableViewDelegate methods...<br>}</pre><p>With this implementation, the prefetchRowsAt method is called when the table view anticipates that cells will soon be displayed. In this method, you can initiate the download of images for the specified IndexPaths in advance, improving the overall performance and user experience by reducing lag and accelerating image loading.</p><p><strong>Implement PrefetchDataSource Protocol</strong></p><p>Once the prefetchDataSource has been implemented, it&#39;s crucial to conform to its protocol. Below is an example of how to adapt the UITableView delegate and data source, along with the UITableViewDataSourcePrefetching protocol, in Swift.</p><pre>extension YourTableViewController: UITableViewDelegate, UITableViewDataSource, UITableViewDataSourcePrefetching {<br>    <br>    // Implement the prefetching method<br>    func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {<br>        for indexPath in indexPaths {<br>            // Check if the operation for the cell at indexPath is nil<br>            if operationCell[indexPath] == nil {<br>                // Retrieve view data from the presenter<br>                guard let viewData = presenter?.viewData as? [ImageCellData] else { return }<br>                <br>                // Create a data loader operation for downloading the image<br>                let dataLoader = DataLoadOperation(viewData[indexPath.row].coverSourceUrl)<br>                <br>                // Add the data loader operation to the operation queue<br>                operationQueue.addOperation(dataLoader)<br>                <br>                // Store the data loader operation in the dictionary with indexPath as the key<br>                operationCell[indexPath] = dataLoader<br>            }<br>        }<br>    }<br>    <br>    // Optional method to cancel prefetching for specific rows<br>    func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) {<br>        for indexPath in indexPaths {<br>            // Check if there is a data loader operation for the indexPath<br>            if let dataLoader = operationCell[indexPath] {<br>                // Cancel the data loader operation<br>                dataLoader.cancel()<br>                <br>                // Remove the data loader operation from the dictionary<br>                operationCell.removeValue(forKey: indexPath)<br>            }<br>        }<br>    }<br>    <br>    // Other UITableViewDelegate and UITableViewDataSource methods...<br>}</pre><p>The prefetchRowsAt method is responsible for initiating prefetch operations, such as downloading images, videos, or other assets required for cells about to be displayed. On the other hand, the cancelPrefetchingForRowsAt method is optional and allows for the cancellation of prefetching operations. This is useful, for instance, when a user abruptly scrolls in the opposite direction, preventing unnecessary downloads for cells that won&#39;t be displayed.</p><p><strong>Configure Existing CellForRowAt</strong></p><p>The next steps involve adjusting the cellForRowAt, willDisplayCell, and didEndDisplaying methods. In cellForRowAt, the focus shifts from downloading assets to setting the necessary data for display, such as starting animations and hide shimmering. The code snippet below demonstrates this adjustment:</p><pre>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>    // Switch statement to handle different cell types<br>    switch cellType {<br>    case .content:<br>        // Dequeue a reusable cell and cast it as ListArticleSmall<br>        guard let cell = tableView.dequeueReusableCell(withIdentifier: ImageCell.identifier) as? ImageCell else {<br>            return UITableViewCell()<br>        }<br>        <br>        // Check if view data is available<br>        if let viewData = presenter?.viewData as? [ImageCellData] {<br>            // Configure the cell with the retrieved data<br>            cell.selectionStyle = .default<br>            cell.configureShimmer(isActive: false)<br>        } else {<br>            // Configure the cell with shimmer animation if view data is not available<br>            cell.configureShimmer(isActive: true)<br>            cell.selectionStyle = .none<br>        }<br>        <br>        // Return the configured cell<br>        return cell<br>    }<br>}</pre><p>In this adjusted cellForRowAt method, the conditional logic ensures that the cell is configured appropriately based on the availability of view data. If data is present, the cell is configured with the necessary information, and animations are started. If data is not available, a shimmer animation is applied to indicate that content is loading. This separation enhances the efficiency of the table view by decoupling the display logic from the download logic, resulting in a smoother user experience.</p><p><strong>Configure Existing WillDisplayMethod</strong></p><p>In the willDisplay function, three conditions need to be checked:</p><ol><li><strong>Asset has been downloaded and is ready:</strong></li></ol><ul><li>This condition verifies whether the asset (presumably an image) has already been downloaded and is in a state of readiness.</li><li>If this condition is met, the code configures the cell with the downloaded image, removes the prefetch operation associated with the current index path (`operationCell.removeValue(forKey: indexPath)`), sets the cell’s selection style, deactivates any shimmer animation, and directly assigns the downloaded image to the cell.</li></ul><p>2.<strong> Asset has been downloaded but is not yet ready:</strong></p><ul><li>This condition checks if the asset for the current cell has been downloaded but is not in a ready state.</li><li>If this condition is satisfied, the code checks whether there is an ongoing prefetch process for the current index (`if let dataLoader = operationCell[indexPath]`). If true, it further examines whether the image has already been downloaded (`if let image = dataLoader.image`).</li><li>If the image is already downloaded, the code configures the cell with the image and performs similar actions as in the first condition. If the image is not yet downloaded, it establishes a closure (`updateCellClosure`) to be executed when the image is ready.</li></ul><p>3. <strong>Asset has not been downloaded</strong></p><ul><li>This condition confirms whether the asset for the current cell has not been downloaded.</li><li>If this condition holds, the code checks whether there is no ongoing prefetch process for the current index (if operationCell[indexPath] == nil). If true, it initiates a prefetch process by creating a DataLoadOperation instance for downloading the asset, sets up the update closure, adds the operation to the operation queue, and associates it with the current index in the operationCell dictionary.</li></ul><p>In summary, these conditions address various scenarios related to downloading and displaying assets in a table view, covering cases where the asset is already downloaded and ready, downloaded but not yet ready, and not downloaded at all.</p><pre>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {<br>    // Checking if the cell is of type ListArticleSmall and presenter&#39;s viewData is available<br>    if let cell = cell as? ImageCell, let viewData = presenter?.viewData as? [ImageCellData] {<br>        <br>        // Closure for updating the cell&#39;s image when the download process is complete<br>        let updateCellClosure: (UIImage?) -&gt; () = { [weak self] image in<br>            guard let self = self else { return }<br>            <br>            // Configuring the cell when the download is complete<br>            operationCell.removeValue(forKey: indexPath)<br>            cell.setImageDirectly(image: image)<br>        }<br>        <br>        // Checking if there is an ongoing prefetch process for this index<br>        if let dataLoader = operationCell[indexPath] {<br>            <br>            if let image = dataLoader.image {<br>                // If there is an image, assign it directly to the cell<br>               <br>                operationCell.removeValue(forKey: indexPath)<br>                cell.setImageDirectly(image: image)<br>            } else {<br>                // If there is no image yet, assign the updateClosure<br>                // so that when the image is ready, it can be assigned to the cell<br>                dataLoader.loadingCompleteHandler = updateCellClosure<br>            }<br>        } else {<br>            // If prefetch process has not occurred, initiate the prefetch<br>            // and assign it to the completion handler for direct assignment when the image is ready<br>            if operationCell[indexPath] == nil {<br>                guard let viewData = presenter?.viewData as? [ListArticleSmallViewCellData] else { return }<br>                let dataLoader = DataLoadOperation(viewData[indexPath.row].coverSourceUrl)<br>                dataLoader.loadingCompleteHandler = updateCellClosure<br>                operationQueue.addOperation(dataLoader)<br>                operationCell[indexPath] = dataLoader<br>            }<br>        }<br>      cell.configureCell(model: viewData[indexPath.row])<br>    }<br>}</pre><p>When didEndDisplayingis triggered, it is essential to halt prefetch operations since they are no longer needed, reducing resource consumption. The code snippet below demonstrates this in Swift:</p><pre>func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {<br>    // If there&#39;s a data loader for this index path and it&#39;s no longer needed,<br>    // cancel the operation and dispose of it.<br>    if let dataLoader = operationCell[indexPath] {<br>        dataLoader.cancel()<br>        operationCell.removeValue(forKey: indexPath)<br>    }<br>}</pre><p><strong>Explanation:</strong></p><p>- This function is invoked when a cell is no longer visible in the table view, indicating that prefetch operations for that cell are no longer required.<br>- It checks whether there is a data loader (prefetch operation) associated with the current index path (operationCell[indexPath]).<br>- If a data loader exists, it is canceled using dataLoader.cancel() to terminate the ongoing prefetch operation.<br>- Subsequently, the data loader is removed from the operationCell dictionary to efficiently manage resources.</p><p>In the given context, the prefetch process is designed to operate in the background, preventing disruption to the main thread and avoiding lag. This is achieved by utilizing the Operation class, built on top of Grand Central Dispatch (GCD). The Operationclass enables concurrent task execution and straightforward cancellation, making it easier to control and manage asynchronous operations. Consequently, a class is created that inherits from the Operation abstraction to encapsulate the prefetching functionality.</p><pre>import SDWebImage<br><br>class DataLoadOperation: Operation {<br>    var image: UIImage?<br>    var loadingCompleteHandler: ((UIImage?) -&gt; ())?<br>    private var urlString: String?<br>    <br>    init(_ urlString: String?) {<br>        self.urlString = urlString<br>    }<br>    <br>    override func main() {<br>        if isCancelled { return }<br>        let replacedUrl = urlString?.replacingOccurrences(of: &quot; &quot;, with: &quot;%20&quot;)<br>        guard let urlString = replacedUrl,<br>              let url = URL(string: urlString)<br>        else { return }<br>        SDWebImageManager.shared.loadImage(<br>            with: url,<br>            options: .continueInBackground,<br>            progress: nil) { [weak self] (image, data, error, cacheType, finished, url) in<br>                guard let self = self else { return }<br>                if error != nil {<br>                    let placeholder = UIImage(image: .placeholder)<br>                    self.image = placeholder<br>                    self.loadingCompleteHandler?(placeholder)<br>                } else {<br>                    self.image = image<br>                    self.loadingCompleteHandler?(self.image)<br>                }<br>            }<br>    }<br>}</pre><p>The purpose of the above code is straightforward: when this operation is executed, it downloads the given URL. Upon completion, the downloaded image is assigned to the image variable, and the loadingCompleted closure is invoked if necessary. Additionally, if there is a cancelation process, the operation is promptly canceled.</p><p>Since the code uses DataLoadOperation, we need to initiate the operation. Therefore, the prefetching code looks like this:</p><pre>let dataLoader = DataLoadOperation(viewData[indexPath.row].coverSourceUrl)<br>operationQueue.addOperation(dataLoader)<br>operationCell[indexPath] = dataLoader</pre><p><strong>Explanation:</strong></p><p>- A DataLoadOperation instance named `dataLoader` is created, responsible for downloading the coverSourceUrl associated with the current cell.<br>- The dataLoader operation is added to the operationQueue in order to execute it asynchronously.<br>- The dataLoaderoperation is then stored in the operationCell dictionary, associated with the current index path. This serves as a way to hold a reference to the operation, allowing access in places such as the willDisplay function and elsewhere in the code.</p><h3><strong>Summary</strong></h3><p>This article explores the challenges of synchronous image loading in UITableView and introduces iOS prefetching as a solution for smoother scrolling. It provides a concise implementation guide, covering the setup of the prefetchDataSource, adoption of UITableViewDataSourcePrefetching, and handling prefetch operations in the tableView(_:prefetchRowsAt:) method.</p><p>The detailed implementation includes adapting UITableViewDelegate and UITableViewDataSource, configuring cellForRowAt and willDisplayCell methods, and addressing various scenarios for asset readiness. To streamline prefetch operations, the article introduces the DataLoadOperation class, utilizing the Operation class for asynchronous image downloading. Instances of this class are managed in an operation queue and stored in the operationCell dictionary for efficient reference.</p><p>In summary, the article guides developers in implementing UITableView prefetching to optimize image loading, improve user experience, and achieve smoother scrolling, utilizing iOS’s built-in capabilities for prefetching.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a12251e2e774" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/swift-uitableview-prefetching-a-guide-to-smoother-scrolling-a12251e2e774">Swift UITableView Prefetching: A Guide to Smoother Scrolling</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying GraphQL with AWS Amplify in Swift: A Step-by-Step Guide for iOS Developers]]></title>
            <link>https://engineering.idn.media/simplifying-graphql-with-aws-amplify-in-swift-a-step-by-step-guide-for-ios-developers-d2a86a253da5?source=rss-1cd75752f934------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2a86a253da5</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Bevan christian]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 09:00:58 GMT</pubDate>
            <atom:updated>2023-10-03T09:00:58.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IvyOGf5PuPdoB40L" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=medium&amp;utm_medium=referral">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this comprehensive guide, iOS developers can embark on a journey to harness the capabilities of AWS Amplify GraphQL for their Swift applications. Say goodbye to months of research and trial and error, as we demystify the implementation process.</p><p>We’ll explore how AWS Amplify, with its extensive backend services and seamless AWS integration, simplifies GraphQL API creation and management. Learn to configure your API, initialize Amplify, and optimize your development workflow.</p><p>Discover how to create queries and subscriptions manually, making your applications more versatile and responsive. We’ll provide practical code examples and tips to navigate the intricacies.</p><p>This guide aims to simplify the Amplify GraphQL implementation process, providing a streamlined path for iOS developers to enhance their cloud-powered applications.</p><h3><strong>Term</strong></h3><p><strong>Amplify</strong></p><p>AWS Amplify is like Firebase but with more extensive backend services and AWS integration. If you’re familiar with Firebase, you’ll find similarities, such as real-time data and authentication. However, Amplify offers even more capabilities, including GraphQL API creation through AWS AppSync, authentication via Amazon Cognito, storage with Amazon S3, and serverless functions with AWS Lambda. While Firebase is great for simplicity, Amplify is ideal for more complex projects that require scalability and seamless integration with other AWS services. So, if you’re comfortable with Firebase, consider Amplify for added power and flexibility in your cloud-powered applications.</p><p><strong>GraphQL</strong></p><p>The Amplify API category provides an interface for retrieving and persisting your model data. The API category comes with default built-in support for AWS AppSync. The Amplify CLI allows you to define your API and provision a GraphQL service with CRUD operations and real-time functionality.</p><h3><strong>Requirements</strong>:</h3><p>You have already created backend resources separately. What we are implementing is only on the frontend side.</p><p>If you don’t have backend resources, I urge you to split the backend resource and frontend because in the documentation, they combine them into one project or monolithic structure, which can be challenging for some developers. And it results in our code structure becoming intertwined and less organized.</p><h3><strong>Let’s Get Started:</strong></h3><p>If you’ve read the documentation provided by Amplify, the first thing we need to do is:</p><p>1. Install AWS CLI <strong>(Skip this part)</strong><br>2. Install Amplify Library<br>3. Configure API <strong>(Skip this part)</strong><br>4. Generate Model Class <strong>(Skip this part)</strong><br>5. Initialize Amplify API</p><p>We can skip steps 1, 3, and 4 for the following reasons:</p><p><strong>Step 1</strong>: We skip this because the purpose of AWS CLI is to pull resources from the backend, make schema changes, and generate code. Essentially, we don’t use all these features because the backend resources are separate from the frontend project.</p><p><strong>Step 3:</strong> We also skip this because we no longer need to set up the schema since it’s already handled by the backend team.</p><p><strong>Step 4:</strong> This feature is usually used with GraphQL. When we use Apollo GraphQL, we take full advantage of the code generation feature. We provide our queries in .graphql files along with our GraphQL schema, and Apollo generates Swift code that we can use to easily develop our application. This feature is also available in Amplify, but it requires including many files. I’ll provide an example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*iej_hbq0nWR84Xc98M0B1w.png" /></figure><p>Imagine that just because we are leveraging the code generation feature, we have to add almost 20 files, even though not all of them are related to our frontend project. So, the steps we need to take are:</p><p><strong>Install amplify library</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*BN6c5569CRzjDF7zH_tUhQ.png" /></figure><p>Go to the project settings and select “Package Dependencies,” then add the package from <a href="https://github.com/aws-amplify/amplify-swift">https://github.com/aws-amplify/amplify-swift</a>. Choose the packages <strong>AWSAPIPlugin</strong> and <strong>Amplify</strong>, and click Add Package.</p><p><strong>Initialize Amplify API</strong></p><pre>func initAmplify() {<br> do {<br>     let apiConfig = APICategoryConfiguration(plugins: IDNAPIConfig().buildConfig())<br>     let config = AmplifyConfiguration(<br>                        analytics: nil,<br>                        api: apiConfig,<br>                        auth: nil,<br>                        dataStore: nil,<br>                        hub: nil,<br>                        logging: nil,<br>                        predictions: nil,<br>                        storage: nil<br>                    )<br>            <br>      try Amplify.add(plugin: AWSAPIPlugin())<br>      try Amplify.configure(config)<br>    } catch {<br>       print(&quot;error&quot;)<br>    }<br>  }<br><br><br>func buildConfig() -&gt; [String: JSONValue] {<br>        return [&quot;awsAPIPlugin&quot;:<br>                    [<br>                        &quot;grapqlName&quot;: [<br>                            &quot;endpointType&quot;: &quot;GraphQL&quot;,<br>                            &quot;endpoint&quot;: &quot;https://swuhsuwswbywssyuws.appsync-api.ap-asia-1.amazonaws.com/graphql&quot;,<br>                            &quot;region&quot;: &quot;ap-asia-1&quot;,<br>                            &quot;authorizationType&quot;: &quot;API_KEY&quot;,<br>                            &quot;apiKey&quot;: &quot;YOUR_API_KEY&quot;<br>                        ]<br>                    ]<br>        ]<br>    }</pre><p>You can include this configuration in the AppDelegate. However, if you already have an `amplifyconfiguration.json` file, you can initialize Amplify like this:</p><pre>func initAmplify() {<br>  do {<br>        try Amplify.add(plugin: AWSAPIPlugin())<br>        try Amplify.configure()<br>        print(&quot;Amplify configured with API plugin&quot;)<br>    } catch {<br>        print(&quot;Failed to initialize Amplify with \(error)&quot;)<br>    }<br>}   </pre><p>What you need to ensure is your endpoint and authorization. In this example, I’m using an API key, but for real projects, you can refer to the code examples in the documentation.</p><p><strong>Queries:</strong><br>Since we are not using code generation from Amplify, we need to perform manual queries, and if there are errors, we have to trace them manually.</p><p>For performing manual queries, you can refer to the following link:<br><a href="https://docs.amplify.aws/lib/graphqlapi/advanced-workflows/q/platform/ios/#combining-multiple-graphql-operations-in-a-single-request">https://docs.amplify.aws/lib/graphqlapi/advanced-workflows/q/platform/ios/#combining-multiple-graphql-operations-in-a-single-request</a></p><pre>extension GraphQLRequest {<br>    static func getPost(byPostId postId: String) -&gt; GraphQLRequest&lt;JSONValue&gt; {<br>        let document = &quot;&quot;&quot;<br>        query getPost($postId: ID!) {<br>          getPost(id: $postId) {<br>            id<br>            title<br>            rating<br>          }<br>        }<br>        &quot;&quot;&quot;<br><br>        return GraphQLRequest&lt;JSONValue&gt;(<br>            document: document,<br>            variables: [<br>                &quot;postId&quot;: postId<br>            ],<br>            responseType: JSONValue.self<br>        )<br>    }<br>    <br>    static func createSubscriptionOnStreamerEvent(roomID: String) -&gt; GraphQLRequest&lt;JSONValue&gt; {<br>        let document = &quot;&quot;&quot;<br>        subscription SubscriptionOnStreamerEvent($roomID: String!) {<br>          onStreamerEvent(roomID: $roomID) {<br>            roomID<br>            eventType<br>            data<br>          }<br>        }<br>        &quot;&quot;&quot;<br><br>        return GraphQLRequest&lt;JSONValue&gt;(<br>            document: document,<br>            variables: [<br>                &quot;roomID&quot;: roomID<br>            ],<br>            responseType: JSONValue.self<br>        )<br>    }<br><br>  static func createNewUser(username: String, email: String, password: String) -&gt; GraphQLRequest&lt;JSONValue&gt; {<br>    let document = &quot;&quot;&quot;<br>    mutation CreateNewUser($username: String!, $email: String!, $password: String!) {<br>      createUser(username: $username, email: $email, password: $password) {<br>        id<br>        username<br>        email<br>      }<br>    }<br>    &quot;&quot;&quot;<br><br>    return GraphQLRequest&lt;JSONValue&gt;(<br>        document: document,<br>        variables: [<br>            &quot;username&quot;: username,<br>            &quot;email&quot;: email,<br>            &quot;password&quot;: password<br>        ],<br>        responseType: JSONValue.self<br>    )<br>}<br>}</pre><p>Code above is a brief example of a query and subscription where the return type is a JSON value. After creating the query, we now need to make the request, and we can do it as follows:</p><pre>func getPost() async {<br>    do {<br>        let result = try await Amplify.API.query(<br>           request: .getPost(byPostId: &quot;oedoedekd&quot;)<br>        )<br><br>        switch result {<br>        case .success(let post):<br>            guard let post = post else {<br>                print(&quot;Could not find post&quot;)<br>                return<br>            }<br>            if let jsonData = post.jsonString?.data(using: .utf8) {<br>               let response = try JSONDecoder().decode(<br>                                    Post.self,<br>                                    from: jsonData<br>                                  )<br>               print(response)        <br>            }<br>        case .failure(let error):<br>            print(&quot;Got failed result with \(error.errorDescription)&quot;)<br>        }<br>    } catch let error as APIError {<br>        print(&quot;Failed to query todo: &quot;, error)<br>    } catch {<br>        print(&quot;Unexpected error: \(error)&quot;)<br>    }<br>}</pre><p>Amplify.API.query(request: the query we created)</p><p>Since we previously added an extension to GraphQLRequest, we can now simply call it using .queryName</p><p>Don’t forget that since the return type is a JSON string, we need to convert it to data and decode the JSON string to place it into our data class.</p><h3><strong>Summary</strong></h3><p>So, the only additions we make to our Swift project are the GraphQL query files containing extensions of GraphQLRequest, the amplifyconfiguration.json file (optional), and the GraphQL request implementations.</p><p>In conclusion, the steps outlined above demonstrate a streamlined approach to implementing Amplify GraphQL, simplifying the process compared to the official documentation and eliminating unnecessary steps. This guide is your shortcut to efficiently harnessing the power of AWS Amplify GraphQL for your iOS applications.</p><p>However, if you don’t have a dedicated backend team and find it challenging to create separate GraphQL resources on the backend, simply follow the steps outlined in the documentation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2a86a253da5" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/simplifying-graphql-with-aws-amplify-in-swift-a-step-by-step-guide-for-ios-developers-d2a86a253da5">Simplifying GraphQL with AWS Amplify in Swift: A Step-by-Step Guide for iOS Developers</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reducing Startup Costs: Developers & Git Hooks for Efficient CI/CD]]></title>
            <link>https://engineering.idn.media/reducing-startup-costs-developers-git-hooks-for-efficient-ci-cd-97403399f8bd?source=rss-1cd75752f934------2</link>
            <guid isPermaLink="false">https://medium.com/p/97403399f8bd</guid>
            <category><![CDATA[unit-test-tools]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[cicd]]></category>
            <dc:creator><![CDATA[Bevan christian]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 13:18:10 GMT</pubDate>
            <atom:updated>2023-08-22T13:18:10.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2t9ysmcIAqJZ52yF" /><figcaption>Photo by <a href="https://unsplash.com/@yancymin?utm_source=medium&amp;utm_medium=referral">Yancy Min</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem</h3><p>We are well aware that we are currently experiencing a tech winter, and our task as developers is to assist the company in surviving during this challenging period. Therefore, I will provide you with a solution for cost-saving. In this case, as developers, we certainly use CI/CD in the development process. Imagine your company has a team of more than 10 people, and with each pull request, PR Testing is performed. There will be numerous PR Testing instances in a day, especially when we are in the midst of a sprint. Without us realizing it, as developers, the resources required to run CI incur significant costs. As a case study, we will focus on the cost of using GitHub Actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*mE4fIXiTx_cLs6e7oKGoPw.png" /></figure><p>Assuming we are utilizing a 12-core vCPU with an average CI/CD process duration of 15 minutes for both building and testing. With a team of 10 developers, each submitting 1 pull request (PR) daily:</p><p><strong>In a single day:</strong><br>(num of developers * PR testing time) * GitHub Actions per-minute rate<br>(10 * 15) * 0.32 = $48</p><p><strong>In a month:</strong><br>$48 * 30 days = $1440/month</p><p>As evident, the cost amounts to $1440 per month. Now, consider if each developer were to perform 3–4 PR tests in a single day, the cost could far surpass the $1440 figure. This highlights the potential financial implications of increased testing frequency.</p><h3>Solution</h3><p>A “git hook,” short for “Git hook,” is a script or program that Git, a distributed version control system, can execute before or after certain events occur in the repository. These hooks enable developers to automate various tasks and workflows in the Git repository. Git hooks are placed in a special directory within the repository’s `.git` directory, and they can be written in any scripting language that can be executed on the system where the repository is located.</p><p>There are two main categories of Git hooks:</p><p>1.<strong> Client-side hooks</strong>: These hooks run on your local machine when you interact with the repository. They don’t affect the repository on the server or the repositories of other developers.</p><p>- pre-commit: This hook runs before a commit is created. It’s commonly used to run code style checks, linting, and other tests to ensure that the code being committed meets certain standards.<br>- pre-push: This hook runs before pushing commits to a remote repository. It’s often used to run additional tests or checks before changes are shared with others.<br>- post-commit and post-update: These hooks run after a commit or update operation is completed. They can be used for tasks like sending notifications or triggering deployment processes.</p><p>2.<strong> Server-side hooks</strong>: These hooks run on the remote server where the Git repository is hosted. They can enforce certain policies or workflows for the entire team or project.</p><p>- pre-receive: This hook is invoked on the server before any references (branches or tags) are updated during a push. It’s often used to enforce certain rules, like rejecting commits that don’t meet certain criteria.<br>- update: This hook is similar to <em>pre-receive</em> but is invoked once for each reference that’s being updated. It’s useful for enforcing more fine-grained controls over different branches.<br>- post-receive: This hook is called after references have been updated on the server. It can be used to trigger actions like deployment to a production environment.</p><p>To use Git hooks, you create executable scripts with specific filenames (matching the hook names) in the `.git/hooks` directory of your repository or you can create your own directory for executable scripts. These scripts can be written in various languages such as Bash, Python, Ruby, or any other language supported by the system.</p><h3>Example</h3><p>In the example below, I will create a pre-push Git hook where every time a user pushes to the repository, unit tests will be executed. If the unit tests fail, the push process will be canceled.</p><p>I will also provide an installation script for the Git hook so that fellow developers don’t have to go through the hassle. Additionally, I have moved the Git hook’s location from `.git/hooks` to its dedicated folder.</p><h4>Create install.sh</h4><p>The first file that needs to be created is `install.sh`. This file is optional since it will only be used once in a lifetime. If you are a solo developer, you can skip this part. However, if you are working with a larger team, this file becomes essential. It allows other team members to set up their Git hooks without needing to know the exact scripts to type.</p><pre># Get the root of the git repository<br>root=$(git rev-parse --show-toplevel) || {<br>    echo &quot;This script must be run within a git repository.&quot;<br>    exit 1<br>}<br><br>target=&quot;$root/githooks&quot;<br><br># Check if the target directory exists<br>if [ ! -d &quot;$target&quot; ]; then<br>    echo &quot;The target directory $target does not exist.&quot;<br>    exit 1<br>fi<br><br># Set local hooks path<br>git config --local core.hooksPath &quot;$target&quot;<br><br># Check if the pre-push file exists before setting it as executable<br>if [ ! -f &quot;$target/pre-push&quot; ]; then<br>    echo &quot;The pre-push hook does not exist.&quot;<br>    exit 1<br>fi<br><br># Set as executable<br>chmod +x &quot;$target/pre-push&quot;<br>echo &quot;Success Install Prepush&quot;</pre><p>With an explanation of the script below:</p><pre>root=$(git rev-parse --show-toplevel) || {<br>    echo &quot;This script must be run within a git repository.&quot;<br>    exit 1<br>}</pre><p>This script ensures that when you run `install.sh`, it is located within a Git repository.</p><pre>target=&quot;$root/githooks&quot;<br><br># Check if the target directory exists<br>if [ ! -d &quot;$target&quot; ]; then<br>    echo &quot;The target directory $target does not exist.&quot;<br>    exit 1<br>fi</pre><p>Then, the script above is used to check if the ‘githook’ folder exists in your app directory.</p><pre># Set local hooks path<br>git config --local core.hooksPath &quot;$target&quot;</pre><p>The script above is used to change the local Git hook path to the desired folder. However, if you don’t want to change the default folder path located in `.git/hooks`, then you can ignore this script.</p><pre># Check if the pre-push file exists before setting it as executable<br>if [ ! -f &quot;$target/pre-push&quot; ]; then<br>    echo &quot;The pre-push hook does not exist.&quot;<br>    exit 1<br>fi<br><br># Set as executable<br>chmod +x &quot;$target/pre-push&quot;<br>echo &quot;Success Install Prepush&quot;</pre><p>This script will make sure that the pre-push script file for the Git hook exists in the location `$root/githooks/pre-push`. If it’s there, then grant access to the script.</p><h4>Create pre-push script</h4><pre># Install dependencies<br>echo &quot;Run PreHook&quot;<br><br># Check if bundler is already installed, and install if not<br>if ! command -v bundle &amp;&gt; /dev/null; then<br>  echo &quot;Bundler not found. Installing...&quot;<br>  gem install bundler<br>  bundle install<br>else<br>  echo &quot;Bundler is already installed.&quot;<br>fi<br><br><br># Check if there are unstaged changes<br>if ! git diff --cached --exit-code; then<br>  echo &quot;Unstaged changes found. Skipping tests.&quot;<br>  exit 0<br>fi<br><br># Replace with your actual commands for running tests<br>bundle exec fastlane pr_tests_local<br>TEST_EXIT_STATUS=$?<br><br># Check exit status of the tests<br>if [ $TEST_EXIT_STATUS -ne 0 ]; then<br>  echo &quot;Tests failed. Aborting push.&quot;<br>  exit 1  # Abort the push<br>fi<br><br>echo &quot;Tests passed. Proceeding with push.&quot;</pre><p>With an explanation of the script below:</p><pre>if ! command -v bundle &amp;&gt; /dev/null; then<br>  echo &quot;Bundler not found. Installing...&quot;<br>  gem install bundler<br>  bundle install<br>else<br>  echo &quot;Bundler is already installed.&quot;<br>fi</pre><p>Script above will Check for Bundler and Install if Needed</p><pre># Check if there are unstaged changes<br>if ! git diff --cached --exit-code; then<br>  echo &quot;Unstaged changes found. Skipping tests.&quot;<br>  exit 0<br>fi</pre><p>The script above then checks if there are any unstaged changes in the repository using the git diff --cached --exit-code command. If there are unstaged changes, it echoes &quot;Unstaged changes found. Skipping tests.&quot; and exits with status code 0, indicating that the script has completed successfully but the push will be skipped.</p><pre># Replace with your actual commands for running tests<br>bundle exec fastlane pr_tests_local<br>TEST_EXIT_STATUS=$?</pre><p>After handling dependencies and unstaged changes, the script runs tests. The specific test command used here is bundle exec fastlane pr_tests_local. This is a command from the Fastlane tool, a popular tool for automating iOS and Android build processes. The script stores the exit status of the tests in the variable TEST_EXIT_STATUS.</p><pre># Check exit status of the tests<br>if [ $TEST_EXIT_STATUS -ne 0 ]; then<br>  echo &quot;Tests failed. Aborting push.&quot;<br>  exit 1  # Abort the push<br>fi<br><br>echo &quot;Tests passed. Proceeding with push.&quot;</pre><p>If the exit status is not equal to 0 (indicating that the tests failed), it echoes “Tests failed. Aborting push.” and exits with status code 1. This status code will prevent the push from being executed.</p><h3>Conclusion</h3><p>Git hooks are powerful tools for automating tasks and ensuring consistency in your development process. However, it’s important to note that hooks are local to each user’s repository, so they won’t be automatically shared with other team members unless explicitly added to the repository.</p><p>This is another way to move PR tests from CI/CD to the local environment. By adopting this approach, we can potentially save thousands of dollars for the company.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97403399f8bd" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/reducing-startup-costs-developers-git-hooks-for-efficient-ci-cd-97403399f8bd">Reducing Startup Costs: Developers &amp; Git Hooks for Efficient CI/CD</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making the Leap from Azure to Codemagic: Achieving a Remarkable 76.85% Improvement in iOS CI/CD]]></title>
            <link>https://engineering.idn.media/making-the-leap-from-azure-to-codemagic-achieving-a-remarkable-76-85-improvement-in-ios-ci-cd-fb6e72925c03?source=rss-1cd75752f934------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb6e72925c03</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[codemagic]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Bevan christian]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 09:01:34 GMT</pubDate>
            <atom:updated>2023-08-15T09:02:41.586Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*whEygwTu2xYJJq74" /><figcaption>Photo by <a href="https://unsplash.com/@lazizli?utm_source=medium&amp;utm_medium=referral">Lala Azizli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Disclaimer</strong></h3><p>This article is purely informational and not sponsored by any particular company or product. The insights and experiences shared are based on genuine observations and intended to provide valuable insights into the discussed topic.</p><h3>Background</h3><p>Before we dive in, make sure you’re comfortable with Fastlane and have some CI/CD experience under your belt.</p><p>In this article, we’re spilling the beans on why we switched from Azure to Codemagic and showing you exactly how to supercharge your CI/CD game. We’re covering the entire spectrum — from compiling and creating release notes to testing and deployment. Let’s rewind a bit to our iOS developers’ struggles. Our CI process (think builds, tests, and coverage) was taking a chunky 40–50 minutes. Even after briefly dipping to 30 minutes, it shot back up due to new features and libraries, putting the brakes on our development speed. And guess what? CD (build and deploy) wasn’t any better, sapping 40 minutes.</p><p>But hold on, Codemagic to the rescue! The magic ingredient? M1 architecture. It turbocharged our build time, shrinking the total ordeal to just 25 minutes, down from the 80–90-minute marathon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*KIHaFDFnBoCN8VsmRhRckw.png" /><figcaption>Build, Test and Deploy in Codemagic 25 Min</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*YVjvFocoxKiPNcP0IhswNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*Bjb_YvfRsW2DgMfngRqTcw.png" /><figcaption>Build, Test and Deploy in Azure 1 Hour 49 Min</figcaption></figure><p>Witness the Marvel: A Whopping <strong>76.85%</strong> Boost in Our CI/CD Process! 🚀</p><h3>Our Script</h3><p>Now, here’s a sneak peek into the goods — a snippet of YAML code for your iOS exploits, complete with testing, building, and the grand finale, deploying to Firebase Distribution.</p><pre> definitions:<br>  - &amp;installDependency <br>    name: Install Dependency<br>    script: |<br>          gem install bundler<br>          bundle install<br><br><br>  - &amp;runTest <br>    name: Run Unit Test<br>    script: | <br>     bundle exec fastlane pr_tests_codemagic<br>        <br>  - &amp;podInstall <br>    name: Install CocoaPods dependencies<br>    script: | <br>     pod install<br><br><br>build-to-firebase-distribution:<br>    name: publish-to-firebase-distribution<br>    max_build_duration: 35<br>    instance_type: mac_mini_m1<br>    cache:<br>      cache_paths:<br>        - $HOME/Library/Caches/CocoaPods<br>    environment:<br>      groups:<br>        - iosVariable<br>        - firebase_credentials<br>      ios_signing:<br>        provisioning_profiles:<br>          - AdHocMobileProvisionCodemagic<br>        certificates:<br>          - distributionCertificate<br>      vars:<br>        BUNDLE_ID: &quot;com.app.App&quot;<br>        XCODE_WORKSPACE: &quot;app.xcworkspace&quot;<br>        XCODE_SCHEME: &quot;release&quot;<br>        TARGET_NAME: &quot;your app name&quot;<br>        APP_STORE_APPLE_ID: xxxx<br>      xcode: 14.2<br>      cocoapods: default<br>    scripts:<br>      - *installDependency<br>      - *podInstall<br>      - *runTest<br>      - name: Generate release notes<br>        script: |<br>             cd $CM_BUILD_DIR <br>             now=$(date)<br>             currentDate=&quot;Current build on $now, This log may not be a complete log, contact developer for the complete build log&quot;<br>             echo $currentDate &gt;&gt; ./release_notes.txt<br>             echo &quot;XCODE_SCHEME: $XCODE_SCHEME&quot; &gt;&gt; ./release_notes.txt<br>             git log --graph --oneline --pretty=format:&quot;%s&quot; --since=&quot;yesterday&quot; &gt;&gt; ./release_notes.txt<br>             cat ./release_notes.txt <br>      - name: Set up provisioning profiles settings on Xcode project<br>        script: xcode-project use-profiles<br>      - name: Get the latest build number and Increment build number<br>        script: |<br>          LATEST_BUILD_VERSION=$(firebase-app-distribution get-latest-build-version -p xxx -a 1:xxx:ios:xxx)<br>          cd $CM_BUILD_DIR # avgtool must run in the folder where xcodeproj file is located<br>          agvtool new-version -all $(($LATEST_BUILD_VERSION + 1))<br>      - name: Build ipa for distribution<br>        script: | <br>          xcode-project build-ipa -v\<br>            --workspace &quot;$CM_BUILD_DIR/$XCODE_WORKSPACE&quot; \<br>            --clean \<br>            --scheme &quot;$XCODE_SCHEME&quot; \<br>            --archive-flags=&quot;-destination &#39;generic/platform=iOS&#39;&quot;    <br>    artifacts:<br>      - build/ios/ipa/*.ipa<br>      - /tmp/xcodebuild_logs/*.log<br>      - $HOME/Library/Developer/Xcode/DerivedData/**/Build/**/*.app<br>      - $HOME/Library/Developer/Xcode/DerivedData/**/Build/**/*.dSYM<br>    publishing:<br>      firebase:<br>        firebase_service_account: $FIREBASE_SERVICE_ACCOUNT<br>        ios:<br>          # Add your iOS app id retrieved from Firebase console<br>          app_id: &quot;1:xxx:ios:xxxx&quot;<br>          # Add one or more groups that you wish to distribute your iOS application to.<br>          # You can create groups in the Firebase console<br>          groups:<br>            - ios-tester<br></pre><p><strong>Fasfile</strong></p><pre>  desc &quot;Run Pull Request tests Codemagic&quot;<br>  lane :pr_tests_codemagic do    <br>    scan(<br>      workspace: &quot;app.xcworkspace&quot;,<br>      scheme: &quot;UnitTesting&quot;,<br>      device: &quot;iPhone SE (3rd generation)&quot;,<br>      reset_simulator: true,<br>      configuration: &quot;debug&quot;, <br>      test_without_building: false,<br>      skip_build: false,<br>      fail_build: false,<br>      number_of_retries: 3,<br>      concurrent_workers: 4<br>    )<br>   if $?.exitstatus != 0<br>     UI.user_error!(&quot;Tests failed. Exiting with status 1.&quot;)<br>     exit(1)<br>   else<br>     UI.success(&quot;Tests passed.&quot;)<br>   end<br>  end</pre><p>This YAML configuration is for setting up a CI/CD pipeline using CodeMagic for an iOS application. It defines a scheduled build named scheduled-build-to-firebase-distribution-RC. The build process includes several steps, such as installing dependencies, running tests, generating release notes, setting up provisioning profiles, incrementing build numbers, setting up code signing, and building the IPA for distribution.</p><p><strong>Build Environment</strong></p><p>The build is performed on a mac_mini_m1 instance.</p><p><strong>Chace</strong></p><pre>cache:<br>      cache_paths:<br>        - $HOME/Library/Caches/CocoaPods</pre><p>CocoaPods caching is used to speed up dependency installation. it will automaticly chace when you execute pod install</p><p><strong>Environment Variables</strong></p><pre>environment:<br>      groups:<br>        - iosVariable<br>        - firebase_credentials</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJLQ5MnOnFv8UF3tmHeN6Q.png" /></figure><p>Various environment variables are defined for the build process, including BUNDLE_ID, XCODE_WORKSPACE, XCODE_SCHEME, TARGET_NAME, and APP_STORE_APPLE_ID. all this environment variables you can set in your app setting in codemagic web</p><p><strong>iOS code signing</strong></p><p>Code signing is a crucial security mechanism in the iOS app development process. It involves adding a digital signature to your app’s executable and other relevant files to verify its authenticity and ensure that it hasn’t been tampered with. Code signing is essential for app distribution and installation on iOS devices.</p><p><strong>Certificate</strong>: Developers generate a request and receive a digital certificate from Apple. This certificate confirms their identity and links their public key to their developer account.</p><p><strong>Provisioning Profile</strong>: A setup file that defines app details, device access, and distribution method. Different types, like development and distribution profiles, are tied to the certificate.</p><pre>ios_signing:<br>        provisioning_profiles:<br>          - AdHocMobileProvisionCodemagic<br>        certificates:<br>          - distributionCertificate</pre><p>because i will publish this app to firebase distribution its mean it will need AdHoc Profiles, if i publish to appstore or testflight you can use App Store profiles.</p><p>to manage this certificate you can go to Team setting -&gt; Integration</p><ol><li>Add your App Store Connect API Key</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTBI3wLXx8P-dESljt9iVQ.png" /></figure><p>after you success add App Store Connect API Key you can proceed to Team setting -&gt; Code Signing indentities</p><ol><li>Upload your p12 file in my case i will name it <em>distributionCertificate</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBWVjl-dvmy5ceAr6vBgFQ.png" /></figure><p>2. After that, fetch your profile — in my case, I will name it AdHocMobileProvisionCodemagic. When fetching profiles, you’ll need an API key from App Store Connect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6PoiXRvwaHgyxXhbfe6vg.png" /></figure><h3>Scripts</h3><p>Several scripts are executed during the build process:</p><p><strong>Install Dependency</strong></p><p>Installs the Bundler gem and installs Ruby dependencies using bundle install.</p><p><strong>Install CocoaPods dependencies</strong></p><p>Installs CocoaPods dependencies using pod install.</p><p><strong>Run Unit Test</strong></p><p>Executes unit tests using Fastlane and the specified lane pr_tests_codemagic.</p><p><strong>Generate Release Notes</strong></p><p>Creates release notes by appending build information, Xcode scheme, and recent commit messages to a text file.</p><pre>- name: Generate release notes<br>  script: |<br>    cd $CM_BUILD_DIR <br>    now=$(date)<br>    currentDate=&quot;Current build on $now, This log may not be a complete log, contact developer for the complete build log&quot;<br>    echo $currentDate &gt;&gt; ./release_notes.txt<br>    echo &quot;XCODE_SCHEME: $XCODE_SCHEME&quot; &gt;&gt; ./release_notes.txt<br>    git log --graph --oneline --pretty=format:&quot;%s&quot; --since=&quot;yesterday&quot; &gt;&gt; ./release_notes.txt</pre><ol><li>cd $CM_BUILD_DIR: This changes the current directory to the $CM_BUILD_DIR, which is a predefined environment variable by codemagic representing the directory where the build is taking place.</li><li>now=$(date): This captures the current date and time using the date command and assigns it to the variable now.</li><li>currentDate=&quot;Current build on $now, This log may not be a complete log, contact developer for the complete build log&quot;: This creates a message indicating the current build timestamp and a note that the log might not be complete, encouraging others to contact the developer for a full log. The variable $now is substituted with the captured date and time.</li><li>echo $currentDate &gt;&gt; ./release_notes.txt: This appends the currentDate message to a file named release_notes.txt.</li><li>echo &quot;XCODE_SCHEME: $XCODE_SCHEME&quot; &gt;&gt; ./release_notes.txt: This appends the value of the XCODE_SCHEME environment variable to the release_notes.txt file. The XCODE_SCHEME is likely a scheme name used in the Xcode project.</li><li>git log --graph --oneline --pretty=format:&quot;%s&quot; --since=&quot;yesterday&quot; &gt;&gt; ./release_notes.txt: This command retrieves the commit history using git log. Commit messages from the Git history, starting from yesterday, are added to the notes file.</li></ol><p><strong>Set up provisioning profiles</strong></p><p>settings on Xcode project: Configures provisioning profiles on the Xcode project.</p><p><strong>Get the latest build number and Increment build number</strong></p><pre>script: |<br>          LATEST_BUILD_VERSION=$(firebase-app-distribution get-latest-build-version -p xxx -a 1:xxx:ios:xxx)<br>          cd $CM_BUILD_DIR # avgtool must run in the folder where xcodeproj file is located<br>          agvtool new-version -all $(($LATEST_BUILD_VERSION + 1))</pre><p>here’s a explanation:</p><ol><li>LATEST_BUILD_VERSION=$(firebase-app-distribution get-latest-build-version -p xxx -a 1:xxx:ios:xxx): Fetches the latest build version from Firebase.</li><li>cd $CM_BUILD_DIR: Navigates to the build directory where the Xcode project file is located.</li><li>agvtool new-version -all $(($LATEST_BUILD_VERSION + 1)): Increases the build version by 1 using agvtool, ensuring a unique identifier for the new build.</li></ol><p><strong>Set up code signing settings on Xcode project:</strong></p><p>Configures code signing settings on the Xcode project.</p><p><strong>Build IPA for distribution</strong>:</p><pre>xcode-project build-ipa -v\<br>            --workspace &quot;$CM_BUILD_DIR/$XCODE_WORKSPACE&quot; \<br>            --clean \<br>            --scheme &quot;$XCODE_SCHEME&quot; \<br>            --archive-flags=&quot;-destination &#39;generic/platform=iOS&#39;&quot;</pre><p>Builds the IPA file for distribution, specifying the workspace, scheme, and archive flags.</p><p>This script is provided by codemagic you can check the documentation in here <a href="https://github.com/codemagic-ci-cd/cli-tools/blob/master/docs/xcode-project/build-ipa.md">https://github.com/codemagic-ci-cd/cli-tools/blob/master/docs/xcode-project/build-ipa.md</a>.</p><h3>Publishing</h3><pre>publishing:<br>      firebase:<br>        firebase_service_account: $FIREBASE_SERVICE_ACCOUNT<br>        ios:<br>          # Add your iOS app id retrieved from Firebase console<br>          app_id: &quot;1:xxx:ios:xxxx&quot;<br>          # Add one or more groups that you wish to distribute your iOS application to.<br>          # You can create groups in the Firebase console<br>          groups:<br>            - ios-tester</pre><p>This script is for publishing to Firebase Distribution, where `$FIREBASE_SERVICE_ACCOUNT` is an environment variable that I’ve set in the `firebase_credentials` environment variable group. The app ID can be found in the Firebase console under Project settings -&gt; Your Apps Section. For the complete documentation, you can refer to this link: <a href="https://docs.codemagic.io/yaml-publishing/firebase-app-distribution/">https://docs.codemagic.io/yaml-publishing/firebase-app-distribution/</a>.</p><h3><strong>Conclusion</strong></h3><p>To sum it up, Codemagic’s M1-powered prowess is our secret sauce for a speedier CI/CD journey. This article unwraps the tech wizardry that slashed build times and ramped up our development mojo. We’re keeping things simple, showing how our YAML wizardry choreographs tests, builds, and deployments like a symphony of efficiency.</p><h3>Next Article</h3><p>The differences between Codemagic and Azure will be discussed in the upcoming article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb6e72925c03" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/making-the-leap-from-azure-to-codemagic-achieving-a-remarkable-76-85-improvement-in-ios-ci-cd-fb6e72925c03">Making the Leap from Azure to Codemagic: Achieving a Remarkable 76.85% Improvement in iOS CI/CD</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleash the Power of Azure Cache: Achieve a 34% Efficiency Boost in CI/CD]]></title>
            <link>https://engineering.idn.media/unleash-the-power-of-azure-cache-achieve-a-34-efficiency-boost-in-ci-cd-11049c544446?source=rss-1cd75752f934------2</link>
            <guid isPermaLink="false">https://medium.com/p/11049c544446</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bevan christian]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 07:21:04 GMT</pubDate>
            <atom:updated>2023-07-11T07:21:04.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i7KhpKd7mX44ybIq" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=medium&amp;utm_medium=referral">freestocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine being a senior iOS developer and hearing phrases like, “Why is our CI/CD taking so long?” or “When will this CI/CD process ever end?” These sentiments are quite common when working on larger applications with complex dependencies involving 3rd-party libraries.</p><p>Initially, CI/CD is meant to be a helpful companion, simplifying the testing and deployment journey. But as your app grows and evolves, the once-loyal companion becomes a burden, plagued by slow performance and frequent failures (we’ve all been victims of timeouts and pesky unit test issues). In this article, we’ll dive into how we can turn this situation around and transform our CI/CD process into a delightful experience, saving us time and headaches along the way. And remember, we’ve already covered the importance of creating fast, isolated, and reliable unit tests in a previous article. So buckle up and let’s explore the thrilling world of optimizing CI/CD performance!</p><p><a href="https://medium.com/idn-engineering/supercharging-unit-tests-my-journey-towards-a-90-reduction-in-test-time-c13ade2ac7a0">Supercharging Unit Tests: Our Journey Towards a 90% Reduction in Test Time</a></p><h3><strong>Problem</strong></h3><p>Here is an example of an Azure Pipelines YAML file to perform build and unit testing every time a user opens a pull request (PR) to the master branch:</p><pre>pr:<br>  - master<br>trigger:<br>  branches:<br>    include:<br>      - master<br><br>pool:<br>  vmImage: &#39;macos-12&#39;<br><br>stages:<br>  - stage: build_test<br>    displayName: &#39;Build and Test&#39;<br>    condition: ne(variables[&#39;Build.Reason&#39;], &#39;Schedule&#39;)<br>    jobs:<br>      - job: job_build_test<br>        displayName: &#39;[Job] Build and Test&#39;<br>        steps:<br>          - script: sudo xcode-select -s /Applications/Xcode_14.2.app/Contents/Developer<br>            displayName: &#39;Select xcode version&#39;<br>          - task: UseRubyVersion@0<br>            inputs:<br>              versionSpec: &#39;~&gt; 3.1&#39;<br>            displayName: &#39;Select ruby version&#39;<br>          - script: gem install bundler<br>            displayName: &#39;Install bundler&#39;<br>          - script: bundle install<br>            displayName: &#39;Install bundler dependencies&#39;<br>          - script: &#39;pod install&#39;<br>            displayName: &#39;Pod install&#39;<br>          - task: Xcode@5<br>            inputs:<br>              xcWorkspacePath: &#39;app.xcworkspace&#39;<br>              scheme: &#39;UnitTesting&#39;<br>              xcodeVersion: &#39;default&#39;<br>              sdk: &#39;iphonesimulator&#39;<br>              configuration: &#39;Debug&#39;<br>              useXcpretty: true<br>              packageApp: true<br>            displayName: &#39;Build app&#39;<br>          - script: bundle exec fastlane pr_tests<br>            displayName: &#39;Test for pull request&#39;<br></pre><p>We can see that in each CI/CD run, we reinstall all the pods/dependencies, which may not be an issue initially. However, as time goes on and the number of pod dependencies increases, the ‘pod install’ time can grow to be around 10–20 minutes or even more (depending on the Azure agent).</p><p><strong>Solution</strong></p><p>Therefore, let’s leverage the cache. If there are no changes in the `Podfile.lock` and the `Podfile`, we can skip the ‘pod install’ step and proceed directly to the build process. This can save us approximately 10–20 minutes(depend on your application).</p><pre>pr:<br>  - master<br>trigger:<br>  branches:<br>    include:<br>      - master<br><br>pool:<br>  vmImage: &#39;macos-12&#39;<br><br>stages:<br>  - stage: build_test<br>    displayName: &#39;Build and Test&#39;<br>    condition: ne(variables[&#39;Build.Reason&#39;], &#39;Schedule&#39;)<br>    jobs:<br>      - job: job_build_test<br>        displayName: &#39;[Job] Build and Test&#39;<br>        steps:<br>          - script: sudo xcode-select -s /Applications/Xcode_14.2.app/Contents/Developer<br>            displayName: &#39;Select xcode version&#39;<br>          - task: UseRubyVersion@0<br>            inputs:<br>              versionSpec: &#39;~&gt; 3.1&#39;<br>            displayName: &#39;Select ruby version&#39;<br>          - script: gem install bundler<br>            displayName: &#39;Install bundler&#39;<br>          - script: bundle install<br>            displayName: &#39;Install bundler dependencies&#39;<br>          - task: Cache@2<br>            displayName: &#39;Cache CocoaPods&#39;<br>            inputs:<br>              key: &#39;pods | &quot;$(Agent.OS)&quot; | Podfile.lock&#39;<br>              path: &#39;Pods&#39;<br>              cacheHitVar: POD_CACHE_RESTORED<br>          - task: CocoaPods@0<br>            displayName: &#39;pod install using the CocoaPods task with defaults&#39;<br>            condition: ne(variables.POD_CACHE_RESTORED, &#39;true&#39;)<br>          - task: Xcode@5<br>            inputs:<br>              xcWorkspacePath: &#39;app.xcworkspace&#39;<br>              scheme: &#39;UnitTesting&#39;<br>              xcodeVersion: &#39;default&#39;<br>              sdk: &#39;iphonesimulator&#39;<br>              configuration: &#39;Debug&#39;<br>              useXcpretty: true<br>              packageApp: true<br>            displayName: &#39;Build app&#39;<br>          - script: bundle exec fastlane pr_tests<br>            displayName: &#39;Test for pull request&#39;</pre><p>Cache@2 and CocoaPods@0 are both tasks used in the Azure Pipelines configuration file (YAML) you provided. Here’s an explanation of each task:</p><ul><li><strong>Cache@2:</strong><br>The `Cache@2` task is used to cache files or directories between pipeline runs. Caching helps improve the performance of subsequent pipeline runs by storing frequently used files or dependencies and retrieving them from the cache instead of downloading them again. In this specific configuration, the `Cache@2` task is used to cache CocoaPods dependencies.</li><li><strong><em>`key`</em></strong>: Specifies a unique key that identifies the cache. In this case, the key is set as `’pods | “$(Agent.OS)” | Podfile.lock’`, which indicates that the cache is specific to the Pods directory, the operating system being used, and the Podfile.lock file.</li><li><strong>`<em>path`</em></strong>: Specifies the path to the directory or files that need to be cached. In this case, it is set to `’Pods’`, indicating that the entire `Pods` directory will be cached.</li><li><strong><em>`cacheHitVar`</em></strong>: Specifies the name of a variable that will be set to `true` if the cache is successfully restored. In this case, it is set as `POD_CACHE_RESTORED`.</li></ul><p>Simply put, if there are any changes in the `Podfile.lock`, operating system version, or `Pod` directory, the cache will be considered invalid, and the ‘pod install’ process will be continued.</p><ul><li><strong>CocoaPods@0</strong>:<br>The `CocoaPods@0` task is used to install CocoaPods dependencies in the project. CocoaPods is a dependency manager for Swift and Objective-C projects. It simplifies the process of adding third-party libraries or frameworks to an iOS or macOS application.</li><li>`<strong>condition</strong>`: Specifies a condition under which the task will be executed. In this case, the `CocoaPods@0` task will only run if the `POD_CACHE_RESTORED` variable is not set to `’true’`. This condition ensures that the task is skipped if the CocoaPods dependencies have already been cached and restored.</li><li>Other than the condition, the `CocoaPods@0` task uses the default settings to install the dependencies. It will execute the `pod install` command in the project directory, resolving and downloading the specified dependencies defined in the Podfile.</li></ul><p>This task is executed when `POD_CACHE_RESTORED` is set to false in order to perform the ‘pod install’ process.</p><p>These tasks are part of the build and test stage of the pipeline and are executed in the specified order in the YAML file. The `Cache@2` task is responsible for caching the CocoaPods dependencies, while the `CocoaPods@0` task installs the dependencies if the cache is not restored.</p><h3><strong>Result:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*L_Fyf2Jj30ExF-r8SZMZ5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*6xuPw5j1uvZEplm4mWcVBQ.png" /><figcaption>After (left) and Before (Right)</figcaption></figure><p>Improvement After 2 Weeks: CI/CD Reduced from 44 Minutes to an Average of 29 Minutes per Day, or 34% Percent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*cvynmnIndlR_GoDYQBYejQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11049c544446" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/unleash-the-power-of-azure-cache-achieve-a-34-efficiency-boost-in-ci-cd-11049c544446">Unleash the Power of Azure Cache: Achieve a 34% Efficiency Boost in CI/CD</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Alamofire Interceptor: Real-Life iOS Case Study]]></title>
            <link>https://engineering.idn.media/unlocking-the-power-of-alamofire-interceptor-real-life-ios-case-study-335c3cc5ac5e?source=rss-1cd75752f934------2</link>
            <guid isPermaLink="false">https://medium.com/p/335c3cc5ac5e</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[alamofire]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Bevan christian]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 03:37:27 GMT</pubDate>
            <atom:updated>2023-07-07T06:49:03.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*33clmDYYPW2OnRK4" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It all started when I was working on a major project at a big startup. There were instances where users would unexpectedly get logged out without any apparent reason, and this had been happening for years, with everyone considering it normal. At first, I also saw it as a common issue, but my curiosity pushed me to investigate further.</p><h3>Problem</h3><p>My focus immediately turned to the Refresh Token process because it was clear that the user logouts happening within specific time intervals were likely caused by problems with the token refresh. The code I encountered was like this, and it took me a while to fully grasp the flow of the token refresh process.</p><pre>class NetworkService {<br>    <br>    var headers: HTTPHeaders = [<br>        &quot;x-api-key&quot;: API_KEY,<br>        &quot;Accept&quot;: &quot;application/json&quot;<br>    ]<br>    <br>    lazy var timeout: TimeInterval = 45 // seconds<br>    <br>    // Temporarily avoiding refresh token - 401 infinite loop by tracking if logic is looping<br>    var hasBeenError: Bool = false<br>    <br>    func request&lt;T: Codable&gt;(<br>        url: String,<br>        parameters: [String: Any] = [:],<br>        token: String? = nil,<br>        method: HTTPMethod = .get,<br>        completion: @escaping ((T?, ErrorResp?) -&gt; Void)<br>    ) {<br>        var apiUrl = &quot;&quot;<br>        <br>        AF.request(<br>            apiUrl,<br>            method: method,<br>            parameters: parameters,<br>            headers: headers<br>        ) { $0.timeoutInterval = self.timeout }<br>            .responseJSON { response in<br>                if User.isLoggedIn {<br>                    if let statusCode = response.response?.statusCode {<br>                        guard statusCode != 401 else { // Point 1<br>                            // Point 2<br>                            if self.hasBeenError == true {<br>                                // Point 3<br>                                self.hasBeenError = false<br>                                self.forceUserRelog()<br>                                return<br>                            }<br>                            // Point 4<br>                            self.hasBeenError = true<br>                            self.refreshToken(<br>                              url: url,<br>                              parameters: parameters,<br>                              method: method,<br>                              token: token,<br>                              completion: completion<br>                             )<br>                            return<br>                        }<br>                        // Point 5<br>                        self.hasBeenError = false<br>                    }<br>                }<br>                switch response.result {<br>                case .success:<br>                    do {<br>                        let jsonDecoder = JSONDecoder()<br>                        if let data = response.data {<br>                            // Handling or Decode data<br>                        } else { }<br>                    } catch let error { }<br>                case .failure(let error):<br>                    // Handling error<br>                }<br>            }<br>    }<br>}</pre><p>The first thing I noticed is:</p><ol><li>The Refresh Token process occurs when the status code is 401 (Unauthorized).</li><li>If a 401 status code is encountered, it enters the body of a guard let statement.</li><li>If a 401 status code is encountered for the second time, or when self.hasBeenError is true, it is considered a failed token refresh process.</li><li>The Refresh Token process takes place, and self.hasBeenError is set to true to track the second attempt when user refresh token again.</li><li>If the Refresh Token is successful, meaning the status code is not 401, then self.hasBeenError is set to false.</li></ol><p>Based on the provided code, it may seem logical when kept simple. However, in reality, this approach is not feasible, which is why users keep experiencing unexpected logouts. This occurs because the developers attempted to create their own mechanism instead of using a more robust solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hewB1d2CzWymIE1e834TQ.png" /><figcaption><a href="https://cloudsundial.com/salesforce-identity/refresh">https://cloudsundial.com/salesforce-identity/refresh</a></figcaption></figure><p>The error arises from</p><ol><li>Using a Singleton pattern for the NetworkService object, which is shared among multiple services.</li><li>Since it is accessed in different places, consider a situation where the user quickly makes API requests to different endpoints. Although the first request may proceed without any problems, the second request can trigger the forceUserRelog process if the token refresh has not yet succeeded, as the hasBeenError flag still remains true.</li></ol><h3>Simple Solution</h3><p>The temporary solution I implemented at that time was by modifying hasBeenError from a Bool to a Dictionary [String: Bool], so that hasBeenError is no longer universal but specific to each URL. This resolved the issue where making requests to different endpoints no longer triggered a forceUserRelog. However, if the same endpoint encounters a refresh token error twice, we would need to add additional logic. This inconsistency is not ideal.</p><h3>Robust Solution: Alamofire Interceptor</h3><p>Alamofire Interceptor is a feature in the Alamofire networking library for iOS and macOS that allows you to intercept and modify network requests and responses.</p><p>Interceptors are functions that can be added to a chain of interceptors that will be called for each request made using Alamofire. These functions can be used to modify the request headers or parameters, add authentication tokens, or even modify the response before it is returned to the caller.</p><p>This feature allows you to centralize common networking functionality, such as handling authentication or refreshing tokens, in one place, and make it available to all network requests made using Alamofire. By using interceptors, you can also avoid having to repeat the same code in multiple places, making your code more maintainable and less error-prone.</p><h3>How its Work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*POGM7wG1JlcjqzWXz3Ozhw.png" /></figure><p>The interceptor process follows the described flow. Prior to sending the request, it enters the adapt function where headers and other necessary information are added. If no errors occur, the process is successfully completed. However, if an error arises and the retry function is invoked, the error code is checked to determine if it corresponds to a 401 error. If it&#39;s not a 401 error, the error is handled conventionally. However, if it is a 401 error, the interceptor triggers the token refresh API call and retries the previously attempted network request.</p><p>This implementation ensures a seamless process of token refresh when needed and automatically retries the network request using the updated token, eliminating the need for manual intervention. It centralizes the token refresh logic, prevents code duplication, and enhances code maintainability, reducing the chances of errors occurring.</p><h3>Changes in Our Code</h3><ol><li>The initial modification implemented was the addition of .validate() in the request to check if the status code falls outside the range of 200 to 299. If the status code is not within this range, the response will be considered an error, and the retry process in the Alamofire interceptor will be triggered. This ensures that only valid responses within the successful status code range proceed without retries, while any errors prompt the interceptor to handle the retry logic.</li></ol><pre>    AF.request(<br>            apiUrl,<br>            method: method,<br>            parameters: parameters,<br>            encoding: encoding,<br>            headers: headers,<br>            interceptor: self<br>        ) { $0.timeoutInterval = self.timeout }<br>            .validate()<br>            .responseJSON { response in }</pre><p>2. Add RequestInterceptor protocol conformation to NetworkService class</p><pre>extension NetworkService: RequestInterceptor {<br><br>    <br>    func adapt(<br>      _ urlRequest: URLRequest,<br>      for session: Session,<br>     completion: @escaping (Result&lt;URLRequest, Error&gt;) -&gt; Void<br>    ) {<br>     // Called before request to set request headers<br>    }<br>    <br>    <br>    func retry(<br>      _ request: Request,<br>      for session: Session,<br>      dueTo error: Error,<br>     completion: @escaping (RetryResult) -&gt; Void) {<br>      // Called when status code is not 200...299 or in failure<br>    }<br><br>}</pre><p>3. The adapt function is added to the NetworkService class because it is required for the class to conform to the RequestInterceptor protocol. This function allows us to add headers to the request before the request process takes place.</p><pre>func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result&lt;URLRequest, Error&gt;) -&gt; Void) {<br>        var request = urlRequest<br><br>        if request.url?.absoluteString.contains(&quot;/refresh-token&quot;) == true {<br>            request.headers = headers<br>            completion(.success(request))<br>        } else {<br>            // Check if there are given token or user token<br>            if let paramToken = token {<br>                headers[&quot;Authorization&quot;] = &quot;Bearer \(paramToken)&quot;<br>            }<br>            request.headers = headers<br>            completion(.success(request))<br>        }<br>    }</pre><p>4. The retry function If a request fails not due to a 401 status code, but for some other reason, the retry mechanism should not be triggered. In such cases, the process should immediately return with the original error, without attempting any retries. This ensures that the error is accurately captured and handled appropriately, without unnecessary retries that wouldn’t resolve the underlying issue.</p><pre>// Called when status code is not 200...299 or in failure<br>    func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -&gt; Void) {<br>        guard let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 else {<br>            // request failed not because 401 but something <br>            // else then do not retry and return with original error<br>            return completion(.doNotRetryWithError(error))<br>        }<br>        guard request.retryCount &lt; retryLimit else {<br>            completion(.doNotRetry)<br>            return<br>        }<br>        <br>        // if we retry then request is not proceed error handling in above<br>        // if doNotRetry then do nothing<br>        AuthService.shared.fetchAuthSession() { [weak self] result in<br>            switch result {<br>            case .success:<br>                completion(.retry)<br>            case .failure:<br>                self?.forceUserRelog()<br>                completion(.doNotRetry)<br>            }<br>        }<br>    }</pre><h3>Conclusion</h3><p>Developers should consider using Alamofire’s interceptor rather than implementing their own refresh token mechanism for several reasons:</p><ol><li>Simplified implementation.</li><li>Reliable and tested solution.</li><li>Centralized logic for easier management.</li><li>Customization options to fit specific needs.</li><li>Community support and updates.</li></ol><p>In summary, using Alamofire’s interceptor offers simplicity, reliability, and flexibility when handling token refreshing, allowing developers to focus on other critical aspects of their application’s development. It provides a battle-tested solution, centralizes the token refreshing logic, and benefits from ongoing community support and updates.</p><h3>Unit Test</h3><p>In the upcoming article, we will perform unit tests on the retry mechanism using the Mocker library. This will allow us to verify the functionality and reliability of the retry process and ensure that it works as intended.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=335c3cc5ac5e" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/unlocking-the-power-of-alamofire-interceptor-real-life-ios-case-study-335c3cc5ac5e">Unlocking the Power of Alamofire Interceptor: Real-Life iOS Case Study</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>