<?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 mohamed ahmed on Medium]]></title>
        <description><![CDATA[Stories by mohamed ahmed on Medium]]></description>
        <link>https://medium.com/@comm.eng_mohamed?source=rss-f8b4e7c957e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t3BBVGuVEhRNIK1iqtTX2g.jpeg</url>
            <title>Stories by mohamed ahmed on Medium</title>
            <link>https://medium.com/@comm.eng_mohamed?source=rss-f8b4e7c957e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:35:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@comm.eng_mohamed/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[Building a Flexible Navigation System in Swift: From UINavigationController to NavigationStack(part…]]></title>
            <link>https://medium.com/@comm.eng_mohamed/navigation-coordinator-explanation-part-2-59b305c156ff?source=rss-f8b4e7c957e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/59b305c156ff</guid>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[coordinator-pattern]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[navigation-architecture]]></category>
            <dc:creator><![CDATA[mohamed ahmed]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 11:13:49 GMT</pubDate>
            <atom:updated>2024-07-20T11:19:32.397Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Flexible Navigation System in Swift: From UINavigationController to NavigationStack<strong>(part 2)</strong></h3><p>part 1 :- <a href="https://medium.com/@comm.eng_mohamed/navigation-coordinator-explanation-part-1-8ab484ceafb8">https://medium.com/@comm.eng_mohamed/navigation-coordinator-explanation-part-1-8ab484ceafb8</a></p><p><strong>Explaining the Route Enum</strong></p><p>Now let’s explain the enum and how it ties everything together.</p><p><strong>Enum for Navigation Flows</strong></p><p>Define an enum to represent the overall navigation routes, incorporating the specific flow routes.</p><pre>public enum Route: View, Hashable {<br>    case flow1(Flow1Route)<br>    <br>    public static func == (lhs: Route, rhs: Route) -&gt; Bool {<br>        switch (lhs, rhs) {<br>        case let (.flow1(route1), .flow1(route2)):<br>            return route1 == route2<br>        }<br>    }<br>    <br>    public func hash(into hasher: inout Hasher) {<br>        switch self {<br>        case .flow1(let route):<br>            hasher.combine(route)<br>        }<br>    }<br>    <br>    public var body: some View {<br>        switch self {<br>        case let .flow1(route):<br>            route<br>        }<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>Route is an enum that wraps specific flow routes, such as Flow1Route.</li><li>It conforms to View to allow direct use in SwiftUI view hierarchies.</li><li>It conforms to Hashable and Equatable to support hashing and equality checking.</li><li>The body property switches over the enum cases to render the appropriate view.</li></ul><p><strong>Putting It All Together</strong></p><p>With the enums and protocols defined, the navigation line makes more sense:</p><p>- mainNav.goTo(.flow1(.secondScreen(mainNav: mainNav, name: name)), presentAs: .push)</p><p>This line navigates to the secondScreen in the flow1 route, using a push presentation style. The enums and protocols ensure that navigation is type-safe and well-structured.</p><p><strong>Multiple Flows and Screens in the Coordinator</strong></p><p>The structure we have defined allows the Coordinator to handle multiple flows, with each flow having its own set of screens. This makes the navigation logic modular and scalable.</p><p>Here’s a summary of how the Coordinator can manage multiple flows:</p><ol><li><strong>Define Separate Enums for Each Flow:</strong></li></ol><ul><li>Each flow, like Flow1, can have its own enum defining the screens and navigation scenarios specific to that flow.</li></ul><ol><li><strong>Wrap Flows in a Unified Route Enum:</strong></li></ol><ul><li>Use a unified enum, like Route, to wrap the different flow enums. This allows the Coordinator to handle multiple flows seamlessly.</li></ul><ol><li><strong>Implement Navigation Methods:</strong></li></ol><ul><li>The Coordinator can implement methods to handle navigation for each flow, ensuring that the logic remains organized and easy to manage.</li></ul><p>Here’s an updated example to illustrate this:</p><p><strong>Enum for a Second Flow</strong></p><p>Define another flow enum, such as Flow2Route.</p><pre>public enum Flow2Route: Hashable {<br>    case thirdScreen(mainNav: NavigationStateProtocol)<br>    case fourthScreen(mainNav: NavigationStateProtocol, detail: String)<br>    <br>    public static func == (lhs: Flow2Route, rhs: Flow2Route) -&gt; Bool {<br>        switch (lhs, rhs) {<br>        case (.thirdScreen, .thirdScreen):<br>            return true<br>        case (.fourthScreen, .fourthScreen):<br>            return true<br>        default:<br>            return false<br>        }<br>    }<br>    <br>    public func hash(into hasher: inout Hasher) {<br>        switch self {<br>        case .thirdScreen:<br>            hasher.combine(0)<br>        case let .fourthScreen(_, detail):<br>            hasher.combine(detail)<br>        }<br>    }<br>}<br><br>extension Flow2Route: View, ThirdScreenCreatorProtocol, FourthScreenCreatorProtocol {<br>    public var body: some View {<br>        switch self {<br>        case let .thirdScreen(mainNav):<br>            createThirdView(router: mainNav)<br>        case let .fourthScreen(mainNav, detail):<br>            createFourthView(router: mainNav, detail: detail)<br>        }<br>    }<br>}</pre><p><strong>Unified Route Enum for Multiple Flows</strong></p><p>Extend the Route enum to include multiple flows.</p><pre>public enum Route: View, Hashable {<br>    case flow1(Flow1Route)<br>    case flow2(Flow2Route)<br>    <br>    public static func == (lhs: Route, rhs: Route) -&gt; Bool {<br>        switch (lhs, rhs) {<br>        case let (.flow1(route1), .flow1(route2)):<br>            return route1 == route2<br>        case let (.flow2(route1), .flow2(route2)):<br>            return route1 == route2<br>        default:<br>            return false<br>        }<br>    }<br>    <br>    public func hash(into hasher: inout Hasher) {<br>        switch self {<br>        case .flow1(let route):<br>            hasher.combine(route)<br>        case .flow2(let route):<br>            hasher.combine(route)<br>        }<br>    }<br>    <br>    public var body: some View {<br>        switch self {<br>        case let .flow1(route):<br>            route<br>        case let .flow2(route):<br>            route<br>        }<br>    }<br>}</pre><p><strong>Coordinator Handling Multiple Flows</strong></p><p>The MainCoordinator can now handle multiple flows and their respective screens.</p><pre>final class MainCoordinator: NavigationStateProtocol {<br>    let router: UINavigationController<br>    <br>    init(router: UINavigationController) {<br>        self.router = router<br>    }<br>    <br>    public func goTo(_ route: Route, presentAs: PresentationType) {<br>        switch presentAs {<br>        case .push:<br>            router.pushViewController(UIHostingController(rootView: route), animated: true)<br>        case let .sheet(height, interactive):<br>            let host = UIHostingController(rootView: route)<br>            host.modalPresentationStyle = .pageSheet<br>            if let sheet = host.sheetPresentationController {<br>                sheet.detents = height<br>                sheet.selectedDetentIdentifier = .medium<br>                sheet.prefersGrabberVisible = false<br>            }<br>            host.isModalInPresentation = interactive<br>            router.present(host, animated: true)<br>        }<br>    }<br>    <br>    func goBack() {<br>        router.popViewController(animated: true)<br>    }<br>    <br>    func dismissSheet() {<br>        router.dismiss(animated: true)<br>    }<br>}</pre><p><strong>Example of FirstView</strong></p><p>Here is how the FirstView looks:</p><pre>public struct FirstView: View {<br>    @State private var router: FirstScreenRouterProtocol<br>    <br>    public init(router: FirstScreenRouterProtocol) {<br>        _router = State(initialValue: router)<br>    }<br>    <br>    public var body: some View {<br>        Button(action: {<br>            router.toSecondScreen(name: &quot;Hello Second Screen 😊&quot;)<br>        }) {<br>            Text(&quot;Second Screen&quot;)<br>        }<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The FirstView struct conforms to the View protocol.</li><li>It has a private state variable router of type FirstScreenRouterProtocol.</li><li>The initializer sets the initial value of router.</li><li>The body property contains a button that, when tapped, triggers the navigation to the second screen via the router.</li></ul><p>This setup ensures that the view is self-contained and capable of handling its own navigation logic through the router passed to it.</p><p><strong>Summary:</strong></p><ul><li>The Coordinator can manage multiple flows, each with its own set of screens.</li><li>Using separate enums for each flow and wrapping them in a unified Route enum ensures a clean and scalable navigation structure.</li><li>The Coordinator handles navigation actions in a modular way, making it easier to maintain and extend the app.</li></ul><p>to Chack to to Migrate to Navigation Stack :- <a href="https://medium.com/@comm.eng_mohamed/navigation-stack-and-dependancies-adf120fb05cd">https://medium.com/@comm.eng_mohamed/navigation-stack-and-dependancies-adf120fb05cd</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59b305c156ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Flexible Navigation System in Swift: From UINavigationController to NavigationStack(part…]]></title>
            <link>https://medium.com/@comm.eng_mohamed/navigation-coordinator-explanation-part-1-8ab484ceafb8?source=rss-f8b4e7c957e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ab484ceafb8</guid>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[coordinator]]></category>
            <category><![CDATA[navigation-architecture]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[mohamed ahmed]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 11:04:22 GMT</pubDate>
            <atom:updated>2024-07-20T11:19:01.742Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Flexible Navigation System in Swift: From UINavigationController to NavigationStack<strong>(part 1)</strong></h3><p><strong>NavigationStack or UINavigationController: A Common Question</strong></p><p>The simplest answer is to check if your application supports iOS versions lower than 16. That’s all</p><p>That’s all. 🤔</p><p><strong>Why Use NavigationStack?</strong></p><p>NavigationStack is powerful and can handle all navigation scenarios. However, you might wonder how to create a navigation flow that can be easily migrated from UINavigationController to NavigationStack.</p><p>In this example, I’ll show you how to build a structured navigation system that can be easily migrated.</p><p><em>First, we need to understand that we will always work with SwiftUI views at the end of the chain. If the view is a UIKit view type (e.g., UIViewController, UITableViewController, etc.), it should always be wrapped in UIViewRepresentable.</em></p><h3><strong>Reasons to Use the Coordinator Pattern</strong></h3><p><strong>Separation of Concerns</strong>:</p><ul><li>By using the Coordinator pattern, view controllers are only responsible for managing their views, not the navigation logic. This leads to cleaner, more maintainable code.</li></ul><p><strong>Reusability</strong>:</p><ul><li>Coordinators can handle the navigation logic for different parts of the app, making it easier to reuse this logic across different view controllers.</li></ul><p><strong>Improved Testing</strong>:</p><ul><li>Since Coordinators handle the navigation, testing the view controllers becomes simpler as you can test them in isolation without worrying about navigation.</li></ul><p><strong>Scalability</strong>:</p><ul><li>As the app grows, the Coordinator pattern helps in managing complex navigation flows more efficiently, avoiding massive view controller classes.</li></ul><p><strong>Decoupling Navigation Logic</strong>:</p><ul><li>By decoupling navigation from view controllers, you can change the flow or presentation logic without touching the view controller code, making your app more flexible.</li></ul><p><strong>Better Organization</strong>:</p><ul><li>It provides a clear structure and flow to the application, making it easier for new developers to understand the navigation logic.</li></ul><h3><strong>Reasons to Use Composite Root</strong></h3><p><strong>Dependency Management</strong>:</p><ul><li>Composite Root helps manage dependencies in a hierarchical manner, making it easier to control and inject dependencies where needed.</li></ul><p><strong>Modular Architecture</strong>:</p><ul><li>It supports a modular approach, allowing different parts of the application to be developed, tested, and maintained independently.</li></ul><p><strong>Improved Testability</strong>:</p><ul><li>By organizing dependencies in a hierarchical manner, it becomes easier to mock and test components in isolation.</li></ul><p><strong>Single Responsibility Principle</strong>:</p><ul><li>Each component or module within the Composite Root pattern has a single responsibility, leading to better code organization and maintainability.</li></ul><p><strong>Scalability</strong>:</p><ul><li>The hierarchical structure allows for better scalability as the application grows, with clear boundaries between different parts of the application.</li></ul><p><strong>Consistency</strong>:</p><ul><li>It ensures a consistent way of managing dependencies and organizing the application, which helps in maintaining code quality over time.</li></ul><h3><strong>Creating the Main Navigation Protocol</strong></h3><p>Let’s start by creating the main navigation protocol, where you can define custom functions to handle uncommon use cases.</p><pre>public enum PresentationType { <br>   case push<br>   case sheet(height: [UISheetPresentationController.Detent], interactive: Bool) <br>}<br><br>public protocol NavigationStateProtocol { <br>   func goTo(_ route: Route, presentAs: PresentationType)<br>   func goBack()<br>   func dismissSheet() <br>}</pre><p><strong>Creating the MainCoordinator Class</strong></p><p>Now, let’s create the MainCoordinator class responsible for all navigation. This class will conform to NavigationStateProtocol.</p><pre>final class MainCoordinator:  NavigationStateProtocol  {<br>    let router: UINavigationController<br>    <br>    init(router: UINavigationController) {<br>        self.router = router<br>    }<br>    <br>    public func goTo(_ route:Route, presentAs: presentationType) {<br>        switch presentAs {<br>        case .push:<br>            router.pushViewController(UIHostingController(rootView: route), animated: true)<br>        case let .sheet(height, interactive):<br>            let host = UIHostingController(rootView: route)<br>            host.modalPresentationStyle = .pageSheet<br>            if let sheet = host.sheetPresentationController {<br>                sheet.detents = height<br>                sheet.selectedDetentIdentifier = .medium<br>                sheet.prefersGrabberVisible = false<br>            }<br>            host.isModalInPresentation = interactive<br>            router.present(host, animated: true)<br>        }<br>    }<br>    <br>    func goBack() {<br>        router.popViewController(animated: true)<br>    }<br>    <br>    func dismissSheet() {<br>        router.dismiss(animated: true)<br>    }<br>}</pre><p>In this implementation:</p><ul><li>The MainCoordinator class conforms to the NavigationStateProtocol.</li><li>It initializes with a UINavigationController to manage navigation.</li><li>The goTo(_:presentAs:) method handles navigation based on the specified presentation type:</li><li>.push for pushing a view controller onto the navigation stack.</li><li>.sheet(height:interactive:) for presenting a view controller as a sheet.</li><li>The goBack() method handles popping the current view controller off the navigation stack.</li><li>The dismissSheet() method handles dismissing a presented sheet.</li></ul><h3><strong>Creating Our Views: FirstView and SecondView</strong></h3><p>Let’s start creating our views, FirstView and SecondView. Each of these views or any number of views (or view controllers) should have the following structure. I’ll continue the example with FirstView.</p><p><strong>Step 1: Define the Protocol</strong></p><p>First, we define a protocol that specifies the navigation scenarios for FirstView.</p><pre>public protocol FirstViewScreenRouterProtocol {<br>    func toSecondScreen(name: String) <br>} </pre><p><strong>Explanation:</strong> The FirstViewScreenRouterProtocol should include all the navigation scenarios for the FirstView screen.</p><p><strong>Step 2: Implement the Router</strong></p><p>Next, we implement the router for the EntryPoint screen.</p><pre>classFirstScreenRouter: FirstViewScreenRouterProtocol {<br>    let mainNav: NavigationStateProtocol<br>    <br>    init(mainNav: NavigationStateProtocol) {<br>        self.mainNav = mainNav<br>    }<br>    <br>    public func toSecondScreen(name: String) {<br>        mainNav.goTo(.flow1(.secondScreen(mainNav: mainNav, name: name)), presentAs: .push)<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The FirstScreenRouter class conforms to the FirstViewScreenRouterProtocol.</li><li>It initializes with a NavigationStateProtocol instance to manage navigation.</li><li>The toSecondScreen(name:) method navigates to the second screen using the goTo(_:presentAs:) method of the NavigationStateProtocol.</li></ul><blockquote><strong>Note:</strong> - mainNav.goTo(.appScreens(.secondScreen(mainNav: mainNav, name: name)), presentAs: .push) line might look complex, but we’ll explain it in detail later.</blockquote><p><strong>Step 3: Define the View Creator Protocol</strong></p><p>We need to define a protocol for creating the views. This protocol will specify how to create the FirstView.</p><pre>public protocol FirstScreenCreatorProtocol {<br>    func createFirstView(router: NavigationStateProtocol) -&gt; FirstView<br>}<br><br>extension FirstScreenCreatorProtocol {<br>    public func createFirstView(router: NavigationStateProtocol) -&gt; FirstView {<br>        FirstView(router: FirstScreenRouter(mainNav: router))<br>    }<br>}<br></pre><p><strong>Explanation:</strong></p><ul><li>The FirstScreenCreatorProtocol defines a method for creating the FirstView.</li><li>An extension of FirstScreenCreatorProtocol provides a default implementation of the createFirstView(router:) method. This implementation initializes the FirstView with a router, specifically an instance of FirstScreenRouter.</li></ul><p><strong>Understanding the Navigation Line</strong></p><p>Now it’s time to jump back to this line:</p><ul><li>mainNav.goTo(.flow1(.secondScreen(mainNav: mainNav, name: name)), presentAs: .push)</li></ul><p>and understand what it does and how to build it. We will discuss it in reverse, starting with:</p><ul><li>.secondScreen(mainNav: mainNav, name: name)<br> <br> <strong>Enum for Navigation Routes</strong></li><li>Define an enum to represent the navigation routes for the flow.</li></ul><pre>public enum Flow1Route: Hashable {<br>    case firstScreen(mainNav: NavigationStateProtocol)<br>    case secondScreen(mainNav: NavigationStateProtocol, name: String)<br>    <br>    public static func == (lhs: Flow1Route, rhs: Flow1Route) -&gt; Bool {<br>        switch (lhs, rhs) {<br>        case (.firstScreen, .firstScreen):<br>            return true<br>        case (.secondScreen, .secondScreen):<br>            return true<br>        default:<br>            return false<br>        }<br>    }<br>    <br>    public func hash(into hasher: inout Hasher) {<br>        switch self {<br>        case .firstScreen:<br>            hasher.combine(0)<br>        case let .secondScreen(_, name):<br>            hasher.combine(name)<br>        }<br>    }<br>}</pre><p><strong>Implementing View Protocols</strong></p><p>Extend Flow1Route to conform to View, FirstScreenCreatorProtocol, and SecondScreenCreatorProtocol.</p><pre>extension Flow1Route: View, FirstScreenCreatorProtocol, SecondScreenCreatorProtocol {<br>    public var body: some View {<br>        switch self {<br>        case let .firstScreen(mainNav):<br>            createFirstView(router: mainNav)<br>        case let .secondScreen(mainNav, name):<br>            createSecondView(router: mainNav, name: name)<br>        }<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>Flow1Route is an enum that defines the possible screens for this navigation flow.</li><li>It conforms to Hashable to support hashing and equality checking.</li><li>The View conformance allows it to be used directly in SwiftUI view hierarchies.</li><li>The protocol conformances (FirstScreenCreatorProtocol and SecondScreenCreatorProtocol) provide methods for creating the respective views.</li></ul><p>In this setup:</p><ul><li>The .secondScreen(mainNav:mainNav, name:name) case is a route for navigating to the second screen.</li><li>The goTo(_:presentAs:) method uses this route to navigate, specifying that the presentation should be a push.</li></ul><p>Check part 2 <a href="https://medium.com/@comm.eng_mohamed/navigation-coordinator-explanation-part-2-59b305c156ff">https://medium.com/@comm.eng_mohamed/navigation-coordinator-explanation-part-2-59b305c156ff</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ab484ceafb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigation Stack and Dependancies (Part 2) Push Notification Handler]]></title>
            <link>https://medium.com/@comm.eng_mohamed/navigation-stack-and-dependancies-part-2-push-notification-handler-9c31c4715f04?source=rss-f8b4e7c957e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c31c4715f04</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[push-notification-ios]]></category>
            <category><![CDATA[swift-push-notification]]></category>
            <category><![CDATA[swiftui-push-notification]]></category>
            <category><![CDATA[push-notification-router]]></category>
            <dc:creator><![CDATA[mohamed ahmed]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 07:58:39 GMT</pubDate>
            <atom:updated>2024-02-07T07:58:39.716Z</atom:updated>
            <content:encoded><![CDATA[<p>Article Follow-Up: Utilizing the Navigator for Push Notification Navigation in SwiftUI</p><p>This article serves as a continuation of the previous installment discussing the Navigation Stack and Dependencies. If you haven’t had the chance to review Part 1, you can find it <a href="https://medium.com/@comm.eng_mohamed/navigation-stack-and-dependancies-adf120fb05cd">here</a>.</p><p>Now, let’s delve into the utilization of the Navigator to handle push notification navigation in SwiftUI.</p><h4>1- App Delagate :-</h4><p>First, we need to create the AppDelegate and obtain an instance from NavigatorApp within it to continue our flow.</p><pre>class AppDelegate: NSObject, UIApplicationDelegate, ObservableObject {<br>    <br>    var app: NavigatorApp?<br>    <br>  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -&gt; Bool {<br>    initialize(application: application, launchOptions: launchOptions)<br>    return true<br>  }<br>    <br>    private func initialize(application: UIApplication, launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {<br>        self.registerForNotifications(application: application)<br>    }<br><br>    func registerForNotifications(application: UIApplication){<br>         UNUserNotificationCenter.current().delegate = self<br>         application.registerForRemoteNotifications()<br>    }<br>}</pre><h4>2- NavigatorApp( @main ) :-</h4><p>Then, upon the onAppear event of the main view, we assign this instance to self, which represents the NavigatorApp.</p><pre>@main<br>struct NavigatorApp: App, MainDependancyContainer {<br>    @UIApplicationDelegateAdaptor private var appDelegate: AppDelegate<br>    @StateObject private var navigator = Navigator.shared<br>    var body: some Scene {<br>        WindowGroup {<br>            NavigationStack(path: $navigationState.mainRoutes) {<br>               dependancyCreator(view: .firstScreen)<br>                    .navigationsConfig()<br>            }<br>              .onAppear {<br>                  appDelegate.app = self<br>              }<br>        }<br>    }<br><br>func handelPushNotification(data: [String:Any]) async {<br>        <br>    }<br><br>}</pre><p>The line @UIApplicationDelegateAdaptor private var appDelegate: AppDelegate in Swift represents a property wrapper used to initialize and manage the AppDelegate instance in a SwiftUI app.</p><p>The function handlePushNotification(data: [String:Any]) serves as the push notification router. It will be accessed by the AppDelegate through the app instance to handle incoming push notifications effectively.</p><pre>extension AppDelegate: UNUserNotificationCenterDelegate{<br>    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {<br>        let userInfo = response.notification.request.content.userInfo<br>        guard let userInfo = userInfo as?[String:Any] else { return }<br>        Task {<br>            await app?.handelPushNotification(data:userInfo)<br>        }<br>    }<br><br>    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -&gt; Void) {<br><br>        return completionHandler([.list, .badge, .sound])<br>    }<br>}</pre><h4>3- func handelPushNotification(data: [String:Any]) async :-</h4><pre>func handelPushNotification(data: [String:Any]) async {<br>        let routeFinder = RouteFinder()<br>    }</pre><p>The RouteFinder() will determine the screen to navigate to based on the data fetched from the push notification.</p><pre>enum PushNotificationTypes: String {<br>    case productDetails<br>}<br>@MainActor<br>struct RouteFinder {<br>func findPushNotifications(data:[String:Any]) async -&gt; Route? {<br>        guard let type = data[&quot;NotificationType&quot;] as? String else { return nil }<br>        switch PushNotificationTypes(rawValue: type) {<br>           case .productDetails:<br>             guard let productID = data[&quot;Id&quot;] as? String else { return nil }<br>            return await ProductPushNotification.openProductDetaisl(id: productID)<br>       }<br>     }<br>}</pre><h4>ProductPushNotification class :-</h4><pre>@MainActor<br>class ProductPushNotification {<br>    static func openProductDetaisl(id: String) async -&gt; Route? {<br>            let product = try! await getProductDetails(id: id)<br>            guard product != nil else { return nil }<br>            return .secondScreen(info: product)<br>    }<br>}</pre><p>The openProductDetails function fetches all necessary information from the backend and returns the route of the required screen.</p><pre>func handelPushNotification(data: [String:Any]) async {<br>        let routeFinder = RouteFinder()<br>        Task {<br>            if let route = await routeFinder.findPushNotifications(data: data) {<br>                    navigator.goTo(route)<br>            }<br>        }<br>    }</pre><p>the Next Article Will Show How To handle DeepLinking Using Navigator 🙂 Soon…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c31c4715f04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigation Stack and Dependancies (Part 1)]]></title>
            <link>https://medium.com/@comm.eng_mohamed/navigation-stack-and-dependancies-adf120fb05cd?source=rss-f8b4e7c957e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/adf120fb05cd</guid>
            <category><![CDATA[swiftuinavigation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[navigation-stack]]></category>
            <category><![CDATA[dependency-container]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[mohamed ahmed]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 11:31:17 GMT</pubDate>
            <atom:updated>2024-02-09T09:23:00.876Z</atom:updated>
            <content:encoded><![CDATA[<h4>In the dynamic landscape of mobile application development, the <em>Navigation Stack</em> serves as the backbone, orchestrating the flow of user interactions with precision and fluidity. Yet, its effectiveness is greatly amplified by two key dependencies: Push Notifications and Deep Linking. These elements, often overlooked in their complexity, play a pivotal role in enhancing user engagement and streamlining user journeys within the application ecosystem.</h4><h4>Push Notifications :-</h4><p>with their ability to deliver timely and personalized messages, have redefined user engagement strategies. They serve as a direct conduit between applications and users, offering valuable updates, promotions, and reminders. However, their seamless integration within the Navigation Stack requires careful orchestration to ensure that they augment, rather than disrupt, the user experience.</p><h4>Deep Linking :-</h4><p>empowers users to navigate directly to specific content or features within an application, bypassing traditional entry points. This functionality not only enhances user convenience but also facilitates a more seamless transition between external stimuli and internal application states. Nevertheless, integrating Deep Linking within the Navigation Stack demands meticulous attention to routing logic and error handling to ensure a cohesive user journey.</p><h4>1- let’s Start by creating Enum for The App Views</h4><pre>public enum AppViews {<br>    //MARK: - Authentication Views<br>    case firstScreen<br>    case secondScreen(info: String)<br>}</pre><p><em>case firstScreen: Defines a case named </em><em>firstScreen. This represents a view related to onboarding in your application.</em></p><p><em>case secondScreen: Defines a case named </em><em>secondScreen. This represents a view where users can enter their info.</em></p><h4>2- MainDependancyContainer</h4><pre>public protocol MainDependancyContainer {<br>    associatedtype T: View<br>    @ViewBuilder<br>    func dependancyCreator(view: AppViews) -&gt; T<br>}</pre><p>t<em>his protocol defines a blueprint for a dependency container that can create views based on the </em><em>AppViews enumeration. It allows for flexibility in specifying the type of view to be created while ensuring that the returned view conforms to the SwiftUI </em><em>View protocol.</em></p><pre>extension MainDependancyContainer {<br>    @MainActor<br>    public func dependancyCreator(view: AppViews) -&gt; some View {<br>        Group {<br>            switch view {<br>            case .firstScreen:<br>                FirstView(router: FirstScreenRouter())<br>            case let .secondScreen(info):<br>                SecondView(router: SecondScreenRouter(), info: info)<br>             }<br>          }<br>       }<br>    }</pre><p><em>This extension provides a default implementation of the </em><em>dependancyCreator function for types conforming to the </em><em>MainDependancyContainer protocol. It creates SwiftUI views based on the provided </em><em>AppViews enumeration cases, utilizing appropriate routers and view models as needed for each view.</em></p><h4>3- Router :-</h4><p>so now let’s Jump to the Router part at the init of the First &amp; Second View</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*BLmybOLX6rCDXQn7uc3LKA.png" /></figure><blockquote>this image shows the folders structure for each flow</blockquote><p>The router component includes the RouterProtocol, encompassing all the navigation actions necessary for managing the flow within this context.</p><pre>public protocol FirstScreenRouterProtocol: AnyObject {<br>    func toSecondScreen(info: String)<br>}<br><br>public protocol SecondScreenRouterProtocol: AnyObject {<br>    func goBack()<br>}</pre><p>Let’s showcase the code representation of FirstView and SecondView.</p><pre>public struct FirstView: View {<br>    @State private var router: FirstScreenRouterProtocol    <br>    public init(router: FirstScreenRouterProtocol) {<br>      _router = State(initialValue: router)<br>    }<br>    <br>    public var body: some View {<br>         Button {<br>                router.toSecondScreen(info: &quot;Hello&quot;)<br>            } label: {<br>                Text(&quot;to Second Screen&quot;)<br>            }<br>   }<br>}<br><br>public struct SecondView: View {<br>    @State private var router: SecondScreenRouterProtocol<br>    public init(router: SecondScreenRouterProtocol) {<br>      _router = State(initialValue: router)<br>    }<br>    <br>    public var body: some View {<br>         Button {<br>                router.goBack()<br>            } label: {<br>                Text(&quot;back&quot;)<br>            }<br>   }<br>}</pre><p>Now, let’s craft FirstScreenRouter() and SecondScreenRouter() that conform to the navigation protocols, encapsulating the navigation actions within their respective contexts.</p><pre>class FirstScreenRouter: FirstScreenRouterProtocol {<br>    <br>    func toSecondScreen(info: String)() {<br>        Navigator.shared.goTo(.secondScreen(info: info))<br>    }<br>}<br><br>class FirstScreenRouter: SecondScreenRouterProtocol {<br>    <br>    func goBack()() {<br>        Navigator.shared.goBack()<br>    }<br>}</pre><h4>4- NavigatorProtocols &amp; Route :-</h4><p>The NavigatorProtocols will include the function responsible for navigation.</p><pre>public protocol NavigatorProtocols {<br>    func goTo(_ route:Route)<br>    func goBack()<br>// Custom navigation functions can be added here.<br>}</pre><pre>public enum Route: Hashable{<br>    case firstScreen<br>    case secondScreen(info: String)<br>}<br><br>extension Route:View, MainDependancyContainer {<br>public var body: some View {<br>        switch self {<br>        case .firstScreen:<br>            dependancyCreator(view: .firstScreen)<br>        case let .secondScreen(info):<br>            dependancyCreator(view: .secondScreen(info: info))<br>        }<br>    }<br>}</pre><h4>4- Navigator Class :-</h4><p>The Navigator class will handle the navigation logic by conforming to the NavigatorProtocols.</p><pre>public final class Navigator: NavigatorProtocols , ObservableObject {<br>    <br>    <br>    @Published public var mainRoutes: [Route] = []<br>    <br>    public static let shared = Navigator()<br><br>    func goTo(_ route:Route) {<br>        mainRoutes.append(route)<br>     }<br><br>    func goBack(){<br>     _ = mainRoutes.popLast()<br>    }<br>}</pre><h4>5- Navigation Modifier :-</h4><pre>public struct NavigationModifier: ViewModifier {<br>    <br>    public func body(content: Content) -&gt; some View {<br>        content<br>            .navigationDestination(for: Route.self) { $0 }<br>    }<br>}<br><br>public extension View {<br>    func navigationsConfig() -&gt; some View {<br>        self.modifier(NavigationModifier())<br>    }<br>}</pre><ul><li>.navigationDestination(for: Route.self): This indicates that the navigationDestination function is being called with a generic type Route. It suggests that this function responsible for determining the navigation destination based on the provided Route type.</li><li>{ $0 }: This is a closure parameter passed to the navigationDestination function. The $0 inside the closure refers to the input parameter passed to the closure. In this context, it indicates that the navigation destination is determined by the input Route itself.</li><li>self.modifier(NavigationModifier())This applies the NavigationModifier modifier to the view (self). NavigationModifier is likely a custom modifier that encapsulates navigation-related configuration or behavior.</li></ul><h4>6- App Entry Point :-</h4><pre>@main<br>struct NavigatorApp: App, MainDependancyContainer {<br>    @StateObject private var navigator = Navigator.shared<br>    var body: some Scene {<br>        WindowGroup {<br>            NavigationStack(path: $navigator.mainRoutes) {<br>               dependancyCreator(view: .firstScreen)<br>                    .navigationsConfig()<br>            }<br>        }<br>    }<br>}</pre><ul><li>NavigationStack: This represents a custom SwiftUI view or component that manages navigation within the app.</li><li>path: $navigator.mainRoutes: This parameter define the navigation path or route within the NavigationStack. The $navigator.mainRoutes is a Binding to an array of Route objects representing the current navigation stack.</li></ul><p>the Next Article Will Show How To handle Push Notifications Using Navigator 🙂</p><p>👉<a href="https://medium.com/@comm.eng_mohamed/navigation-stack-and-dependancies-part-2-push-notification-handler-9c31c4715f04">link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adf120fb05cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine Network Layer Like (Moya)]]></title>
            <link>https://medium.com/@comm.eng_mohamed/combine-network-layer-like-moya-b54780719099?source=rss-f8b4e7c957e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b54780719099</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swift-networking]]></category>
            <category><![CDATA[network-layer-protocol]]></category>
            <category><![CDATA[combine-network-layer]]></category>
            <dc:creator><![CDATA[mohamed ahmed]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 13:13:39 GMT</pubDate>
            <atom:updated>2024-02-03T15:58:28.828Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello All in this Article i’m going to build a Generic Network Layer Using Combine and and how to use it in 20 Steps</p><h4>In Swift, as in many programming languages, a generic networking layer can provide several benefits:</h4><ol><li>Abstraction: A generic networking layer can abstract away low-level networking details, making it easier to work with APIs and reducing code duplication across different parts of your application.</li><li>Modularity: By encapsulating networking logic in a separate layer, you can modularize your codebase, making it easier to maintain and test.</li><li>Flexibility: A generic networking layer can be designed to support various networking tasks, such as making HTTP requests, handling responses, authentication, error handling, and more. This flexibility allows you to adapt your networking layer to different requirements and APIs.</li><li>Reusability: Once you’ve implemented a generic networking layer, you can reuse it across different projects or modules within the same project, saving time and effort.</li><li>Encapsulation: By encapsulating networking logic in a separate layer, you can improve the overall organization and structure of your codebase, adhering to principles of encapsulation and separation of concerns.</li><li>Testability: Separating networking logic into its own layer makes it easier to write unit tests for that logic, as you can mock network responses and simulate various scenarios without actually making real network requests.</li></ol><p>Overall, a generic networking layer in Swift can help improve the maintainability, scalability, and testability of your codebase while providing a clean and consistent interface for interacting with network resources.</p><p>so let’s Start</p><p>First Let’s Build the Network Layer in 12 Steps</p><h3>1- NetworkingAppDefault</h3><pre>import Foundation<br> <br>public enum AppDefaultsKeys : String {<br>    case baseUrl<br>}<br><br><br>internal class ValueWrapper&lt;T: Codable&gt; : Codable {<br>    var value: T<br>    <br>    init(value: T) {<br>        self.value = value<br>    }<br>}<br><br>class NetworkingAppDefault {<br>    <br>    public static let shared = NetworkingAppDefault()<br>    <br>    fileprivate init() {<br>    }<br>    <br>    fileprivate let userDefaults = UserDefaults.standard<br>    <br>    func save&lt;T: Codable&gt;(_ object: T, forKey key: AppDefaultsKeys) {<br>        let wrappedValue = ValueWrapper(value: object)<br>        guard let encoded = try? JSONEncoder().encode(wrappedValue) else { return }<br>        userDefaults.set(encoded, forKey: key.rawValue)<br>    }<br>    <br>    func get&lt;T: Codable&gt;(_ key: AppDefaultsKeys) -&gt; T? {<br>        if let wrappedObjectData = userDefaults.value(forKey: key.rawValue) {<br>            do {<br>                let obj: ValueWrapper&lt;T&gt; = try JSONDecoder().decode(ValueWrapper&lt;T&gt;.self, from: wrappedObjectData as! Data)<br>                return obj.value<br>            }catch {<br>                return nil<br>            }<br>        }else{<br>            return nil<br>        }<br>    }<br>    <br>    <br>    func get&lt;T: Codable&gt;(_ key: AppDefaultsKeys, orReturn defVal: T) -&gt; T {<br>        let retreivedObj: T? = self.get(key)<br>        if retreivedObj == nil{<br>            return defVal<br>        }<br>        return retreivedObj!<br>    }<br><br>}</pre><blockquote>We will utilize NetworkingAppDefault to define the baseURL.</blockquote><h3>2- AppConfigManager</h3><pre>import Foundation<br><br>enum AppBaseURL: String, Codable {<br>    case staging = &quot;https://api.football-data.org&quot;<br>    <br>}<br><br><br>class AppConfigManager {<br>    static let shared = AppConfigManager()<br>    <br>    //MARK: BaseURL<br>    func selectBaseUrl(_ url: AppBaseURL) {<br>        NetworkingAppDefault.shared.save(url, forKey: .baseUrl)<br>    }<br>    <br>    func getSelectedBaseURL() -&gt; String {<br>        guard let baseUrl: AppBaseURL = NetworkingAppDefault.shared.get(.baseUrl) else { return AppBaseURL.staging.rawValue }<br>        return baseUrl.rawValue<br>    }<br>}</pre><blockquote>We will employ AppConfigManager to ascertain the current development environment.</blockquote><h3>3- ParameterEncoder &amp; NetworkError</h3><pre>import Foundation<br><br>public typealias Parameters = [String:Any]<br><br>public protocol ParameterEncoder {<br>    func encode(urlRequest: inout URLRequest, with parameters: Parameters) throws<br>}<br><br>public enum NetworkError : String, Error {<br>    case parametersNil = &quot;Parameters were nil.&quot;<br>    case encodingFailed = &quot;Parameter encoding failed.&quot;<br>    case missingURL = &quot;URL is nil.&quot;<br>}</pre><p>This Swift file defines a set of components related to parameter encoding for network requests. It includes a typealias Parameters representing a dictionary of string keys and any values, a protocol ParameterEncoder for encoding parameters into a URLRequest, and an enum NetworkError for representing errors related to parameter encoding and network requests.</p><p>Key Components:</p><h4>Typealias Parameters:</h4><ul><li>Represents a dictionary with string keys and values of any type. This typealias is commonly used to pass parameters to network requests.</li></ul><h4>Protocol ParameterEncoder:</h4><ul><li>Defines a blueprint for types capable of encoding parameters into a URLRequest.</li><li>Requires conforming types to implement a method encode(urlRequest:with:) which modifies the provided URLRequest with the given parameters.</li></ul><h4>Enum NetworkError:</h4><ul><li>Represents various error cases related to network requests and parameter encoding.</li><li>Cases include:</li><li>parametersNil: Indicates that parameters provided for encoding were nil.</li><li>encodingFailed: Indicates that parameter encoding failed for some reason.</li><li>missingURL: Indicates that the URL used in the URLRequest is nil.</li></ul><blockquote>This file encapsulates functionality related to parameter encoding and error handling in network requests. It provides a foundation for implementing custom parameter encoding strategies and handling errors that may occur during the encoding process or network requests in general.</blockquote><h3>4- JSONParameterEncoder</h3><pre>import Foundation<br><br>public struct JSONParameterEncoder: ParameterEncoder {<br>    public func encode(urlRequest: inout URLRequest, with parameters: Parameters) throws {<br>        do {<br>            let jsonAsData = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)<br>            urlRequest.httpBody = jsonAsData<br>            if urlRequest.value(forHTTPHeaderField: &quot;Content-Type&quot;) == nil {<br>                urlRequest.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>            }<br>        }catch {<br>            throw NetworkError.encodingFailed<br>        }<br>    }<br>}</pre><p>This Swift file defines a struct JSONParameterEncoder that conforms to the ParameterEncoder protocol. It provides an implementation for encoding parameters into a JSON format for use in network requests. The file relies on the Foundation framework.</p><p>Key Components:</p><h4>Struct JSONParameterEncoder:</h4><ul><li>Represents a parameter encoder specifically designed for encoding parameters into a JSON format.</li><li>Conforms to the ParameterEncoder protocol, indicating its capability to encode parameters into a URLRequest.</li><li>Implements the encode(urlRequest:with:) method required by the ParameterEncoder protocol. Within this method:</li><li>It attempts to serialize the provided parameters into JSON data using JSONSerialization.data(withJSONObject:options:).</li><li>If successful, it sets the HTTP body of the URLRequest to the serialized JSON data.</li><li>Additionally, it checks if the URLRequest does not already have a “Content-Type” header field set, and if not, it sets it to “application/json”.</li><li>If any error occurs during the serialization process, it throws a NetworkError.encodingFailed error.</li></ul><blockquote>This file encapsulates the functionality of encoding parameters into a JSON format suitable for use in network requests. The JSONParameterEncoder struct provides a standardized way to prepare data for transmission over a network when working with APIs that accept JSON payloads. It promotes code reusability and adheres to the principles of separation of concerns by providing a dedicated component for parameter encoding.</blockquote><h3>5- URLParameterEncoder</h3><pre>import Foundation<br><br>public struct URLParameterEncoder: ParameterEncoder {<br>    public func encode(urlRequest: inout URLRequest, with parameters: Parameters) throws {<br>        <br>        guard let url = urlRequest.url else { throw NetworkError.missingURL }<br>        <br>        if var urlComponents = URLComponents(url: url,<br>                                             resolvingAgainstBaseURL: false), !parameters.isEmpty {<br>            <br>            urlComponents.queryItems = [URLQueryItem]()<br>            <br>            for (key,value) in parameters {<br>                let queryItem = URLQueryItem(name: key,<br>                                             value: &quot;\(value)&quot;.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))<br>                urlComponents.queryItems?.append(queryItem)<br>            }<br>            urlRequest.url = urlComponents.url<br>        }<br>        <br>        if urlRequest.value(forHTTPHeaderField: &quot;Content-Type&quot;) == nil {<br>            urlRequest.setValue(&quot;application/x-www-form-urlencoded; charset=utf-8&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>        }<br>        <br>    }<br>}</pre><p>This Swift file defines a struct URLParameterEncoder that conforms to the ParameterEncoder protocol. It provides an implementation for encoding parameters into URL query parameters for use in network requests. The file relies on the Foundation framework.</p><p>Key Components:</p><h4>Struct URLParameterEncoder:</h4><ul><li>Represents a parameter encoder specifically designed for encoding parameters into URL query parameters.</li><li>Conforms to the ParameterEncoder protocol, indicating its capability to encode parameters into a URLRequest.</li><li>Implements the encode(urlRequest:with:) method required by the ParameterEncoder protocol. Within this method:</li><li>It first checks if the provided URLRequest has a valid URL, throwing a NetworkError.missingURL error if the URL is nil.</li><li>It constructs a new URLComponents instance based on the existing URL of the URLRequest.</li><li>If the parameters dictionary is not empty, it iterates through the key-value pairs and adds URLQueryItem instances to the URLComponents queryItems array, with the values percent-encoded to ensure URL safety.</li><li>After constructing the query parameters, it updates the URLRequest’s URL with the modified URLComponents URL.</li><li>It also checks if the URLRequest does not already have a “Content-Type” header field set, and if not, it sets it to “application/x-www-form-urlencoded; charset=utf-8”.</li></ul><blockquote>This file encapsulates the functionality of encoding parameters into URL query parameters suitable for use in network requests. The URLParameterEncoder struct provides a standardized way to prepare data for transmission over a network when working with APIs that accept URL query parameters. It promotes code reusability and adheres to the principles of separation of concerns by providing a dedicated component for parameter encoding.</blockquote><h3>6- ParameterEncoding</h3><pre>public enum ParameterEncoding {<br>    <br>    case urlEncoding<br>    case jsonEncoding<br>    case urlAndJsonEncoding<br>    <br>    public func encode(urlRequest: inout URLRequest, bodyParameters: Parameters?, urlParameters: Parameters?) throws {<br>        do {<br>            switch self {<br>            case .urlEncoding:<br>                guard let urlParameters = urlParameters else { return }<br>                try URLParameterEncoder().encode(urlRequest: &amp;urlRequest,<br>                                                 with: urlParameters)<br>                <br>            case .jsonEncoding:<br>                guard let bodyParameters = bodyParameters else { return }<br>                try JSONParameterEncoder().encode(urlRequest: &amp;urlRequest,<br>                                                  with: bodyParameters)<br>                <br>            case .urlAndJsonEncoding:<br>                guard let bodyParameters = bodyParameters, let urlParameters = urlParameters else { return }<br>                try URLParameterEncoder().encode(urlRequest: &amp;urlRequest,<br>                                                 with: urlParameters)<br>                try JSONParameterEncoder().encode(urlRequest: &amp;urlRequest,<br>                                                  with: bodyParameters)<br>            }<br>        }catch {<br>            throw error<br>        }<br>    }<br>}</pre><p>This Swift file defines an enumeration ParameterEncoding that represents different encoding strategies for parameters in network requests. It includes cases for URL encoding, JSON encoding, and a combination of URL and JSON encoding. The file relies on the Foundation framework.</p><p>Key Components:</p><h4>Enum ParameterEncoding:</h4><ul><li>Represents different strategies for encoding parameters in network requests.</li></ul><h4>Cases include:</h4><ul><li>urlEncoding: Indicates encoding parameters into URL query parameters.</li><li>jsonEncoding: Indicates encoding parameters into a JSON format.</li><li>urlAndJsonEncoding: Indicates encoding parameters into both URL query parameters and a JSON format.</li><li>Provides a method encode(urlRequest:bodyParameters:urlParameters:) to encode parameters into the specified format.</li><li>Within this method:</li><li>It switches on the enum’s cases and uses corresponding parameter encoder structs (URLParameterEncoder and JSONParameterEncoder) to perform the encoding.</li><li>Depending on the selected encoding strategy, it optionally encodes body parameters, URL parameters, or both, into the provided URLRequest.</li></ul><blockquote>This file encapsulates the functionality of encoding parameters into different formats for use in network requests. The ParameterEncoding enumeration provides a standardized way to specify encoding strategies, promoting code reusability and adherence to the principles of separation of concerns by abstracting away the details of parameter encoding from the client code.</blockquote><h3>7- HTTPMethod</h3><pre>import Foundation<br><br>public enum HTTPMethod : String {<br>    case get     = &quot;GET&quot;<br>    case post    = &quot;POST&quot;<br>    case put     = &quot;PUT&quot;<br>    case patch   = &quot;PATCH&quot;<br>    case delete  = &quot;DELETE&quot;<br>}</pre><h3>8- HTTPHeaders &amp; HTTPTask</h3><pre>import Foundation<br><br>public typealias HTTPHeaders = [String:String]<br><br>public var defaultHeaders: HTTPHeaders {<br>    get{<br>        var header = HTTPHeaders()<br>        header[&quot;Content-Type&quot;] = &quot;application/json&quot;<br>        header[&quot;X-Auth-Token&quot;] = &quot;******************&quot;<br>        return header<br>    }<br>}<br><br>public enum HTTPTask {<br>    case request<br>    <br>    case requestParameters(bodyParameters: Parameters?,<br>        bodyEncoding: ParameterEncoding,<br>        urlParameters: Parameters?)<br>    <br>    case requestParametersAndHeaders(bodyParameters: Parameters?,<br>        bodyEncoding: ParameterEncoding,<br>        urlParameters: Parameters?,<br>        additionHeaders: HTTPHeaders?)<br>    <br>    case requestMultiPart(bodyParameters: Parameters?,<br>          bodyEncoding: ParameterEncoding,<br>          urlParameters: Parameters?,<br>          additionHeaders: HTTPHeaders?,<br>          imageFile: MultiPartBodyFile?)<br>}<br><br>public struct MultiPartBodyFile {<br>    var fileUrl: URL!<br>    var fileData: Data!<br>    var fileName: String!<br>    var fileMimeType: String!<br>    <br>    init(fileData: Data, name: String!, mimeType: String!) {<br>        self.fileData = fileData<br>        self.fileName = name<br>        self.fileMimeType = mimeType<br>    }<br>}</pre><p>This Swift file defines several components related to HTTP requests, including HTTP headers, a set of default headers, various types of HTTP tasks, and a structure for representing multipart body files. The file relies on the Foundation framework.</p><p>Key Components:</p><h4>Typealias HTTPHeaders:</h4><ul><li>Represents a dictionary with string keys and string values, used to store HTTP headers.</li></ul><h4>Computed Variable defaultHeaders:</h4><ul><li>Provides a set of default HTTP headers commonly used in API requests.</li><li>Includes headers for specifying the content type as JSON and an example token header (obfuscated with asterisks).</li></ul><h4>Enum HTTPTask:</h4><ul><li>Defines different types of HTTP tasks that can be performed in a network request.</li><li>Cases include:</li><li>request: Represents a simple request without any parameters or additional headers.</li><li>requestParameters: Represents a request with body parameters, URL parameters, and specified encoding for body parameters.</li><li>requestParametersAndHeaders: Represents a request with body parameters, URL parameters, additional headers, and specified encoding for body parameters.</li><li>requestMultiPart: Represents a request with multipart form data, including body parameters, URL parameters, additional headers, and a file to be uploaded.</li></ul><h4>Struct MultiPartBodyFile:</h4><ul><li>Represents a multipart form data file to be included in an HTTP request.</li><li>Contains properties for the file URL, file data, file name, and file MIME type.</li><li>Provides an initializer to create a multipart body file with the specified data, name, and MIME type.</li></ul><blockquote>This file encapsulates functionality related to HTTP requests, including defining headers, specifying different types of HTTP tasks, and representing multipart form data files. It provides a standardized way to define and configure components necessary for making HTTP requests in Swift-based applications.</blockquote><h3>9- ServerPaths</h3><pre>import Foundation<br><br>public enum ServerPaths: String {<br>    case leages = &quot;competitions&quot;<br>    case teams = &quot;competitions/{0}/teams&quot;<br>    case matches = &quot;teams/{0}//matches&quot;<br>}</pre><h3>10- EndPointType</h3><pre>import Foundation<br><br><br>public protocol EndPointType {<br>    var baseURL: URL { get }<br>    var path: ServerPaths { get }<br>    var pathArgs: [String]? { get }<br>    var httpMethod: HTTPMethod { get }<br>    var task: HTTPTask { get }<br>    var headers: HTTPHeaders? { get }<br>}<br><br>extension EndPointType {<br>    <br>    var environmentBaseURL : String {<br>        return &quot;\(AppConfigManager.shared.getSelectedBaseURL())/v4&quot;<br>    }<br>    <br>    public var baseURL: URL {<br>        guard let url = URL(string: environmentBaseURL) else { fatalError(&quot;baseURL could not be configured.&quot;)}<br>        return url<br>    }<br>    <br>    var pathArgs: [String]?  {<br>        return nil<br>    }<br>    <br>    var requestURL: URL {<br>        return baseURL.appendingPathComponent(path.rawValue.formatted(with: self.pathArgs))<br>    }<br><br>}<br><br><br>extension String {<br>    func formatted(with args: [String]?) -&gt; String {<br>        guard let args = args, args.count &gt; 0 else {<br>            return self<br>        }<br>        var data = self<br>        for i in 0...args.count - 1 {<br>            data =  data.replacingOccurrences(of: &quot;{\(i)}&quot;, with: args[i])<br>        }<br>        return data<br>    }<br>}</pre><h3>11- Router</h3><pre>import Foundation<br>import Combine<br>import UIKit<br><br>protocol NetworkRouter: AnyObject {<br>    associatedtype EndPoint: EndPointType<br>    func request(_ route: EndPoint) -&gt; AnyPublisher&lt;(Data,URLResponse), Error&gt;<br>}<br><br>fileprivate var networkActivityCount: Int = 0 {<br>    didSet {<br>        DispatchQueue.main.async {<br>            UIApplication.shared.isNetworkActivityIndicatorVisible = (networkActivityCount &gt; 0)<br>        }<br>    }<br>}<br><br>class Router&lt;EndPoint: EndPointType&gt;: NetworkRouter {<br>    var cancellables = Set&lt;AnyCancellable&gt;()<br>    <br>    func request(_ route: EndPoint) -&gt; AnyPublisher&lt;(Data,URLResponse), Error&gt; {<br>        return Future { promise in<br>            self.buildRequest(from: route)<br>                .flatMap(maxPublishers: .max(1),{ info -&gt; AnyPublisher&lt;(Data,URLResponse), Error&gt; in<br>                    self.performRequest(info)<br>                })<br>                .sink { completion in<br>                    if case let .failure(error) = completion {<br>                        promise(.failure(error))<br>                    }<br>                } receiveValue: { data in<br>                    promise(.success(data))<br>                }.store(in: &amp;self.cancellables)<br>        }.eraseToAnyPublisher()<br>    }<br>    <br>    func performRequest(_ request: URLRequest) -&gt; AnyPublisher&lt;(Data,URLResponse), Error&gt; {<br>        return Future { promise in<br>            URLSession.shared.dataTaskPublisher(for: request)<br>                .sink { error in<br>                    if case let .failure(error) = error {<br>                        promise(.failure(error))<br>                    }<br>                } receiveValue: { info in<br>                    promise(.success(info))<br>                }.store(in: &amp;self.cancellables)<br>        }.eraseToAnyPublisher()<br>    }<br>    <br>    <br>    fileprivate func buildRequest(from route: EndPoint) -&gt; AnyPublisher&lt;URLRequest,Error&gt; {<br>        return Future { promise in<br>            var request = URLRequest(url: route.requestURL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30.0)<br>            request.httpMethod = route.httpMethod.rawValue<br>            do {<br>                switch route.task {<br>                case .request:<br>                    request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>                    <br>                case .requestParameters(let bodyParameters,<br>                                        let bodyEncoding,<br>                                        let urlParameters):<br>                    <br>                    try self.configureParameters(bodyParameters: bodyParameters,<br>                                                 bodyEncoding: bodyEncoding,<br>                                                 urlParameters: urlParameters,<br>                                                 request: &amp;request)<br>                    <br>                case let .requestParametersAndHeaders(bodyParameters, bodyEncoding, urlParameters, additionalHeaders):<br>                    <br>                    self.addAdditionalHeaders(additionalHeaders,<br>                                              request: &amp;request)<br>                    try self.configureParameters(bodyParameters: bodyParameters,<br>                                                 bodyEncoding: bodyEncoding,<br>                                                 urlParameters: urlParameters,<br>                                                 request: &amp;request)<br>                    <br>                case .requestMultiPart(let bodyParameters, let bodyEncoding, let urlParameters, let additionHeaders, let multipartFile):<br>                    self.addAdditionalHeaders(additionHeaders, request: &amp;request)<br>                    self.configureMultiPart(bodyParameters, bodyEncoding, urlParameters, multipartFile, &amp;request)<br>                }<br>                promise(.success(request))<br>            } catch {<br>                promise(.failure(error))<br>            }<br>        }.eraseToAnyPublisher()<br>    }<br>    <br>    fileprivate func configureParameters(bodyParameters: Parameters?, bodyEncoding: ParameterEncoding, urlParameters: Parameters?, request: inout URLRequest) throws {<br>        do {<br>            try bodyEncoding.encode(urlRequest: &amp;request,<br>                                    bodyParameters: bodyParameters,<br>                                    urlParameters: urlParameters)<br>        } catch {<br>            throw error<br>        }<br>    }<br>    <br>    fileprivate func addAdditionalHeaders(_ additionalHeaders: HTTPHeaders?, request: inout URLRequest) {<br>        guard let headers = additionalHeaders else { return }<br>        for (key, value) in headers {<br>            request.setValue(value, forHTTPHeaderField: key)<br>        }<br>    }<br>    <br>    fileprivate func configureMultiPart(_ bodyParameters: Parameters?,<br>                                        _ bodyEncoding: ParameterEncoding,<br>                                        _ urlParameters: Parameters?,<br>                                        _ multiPartFile: MultiPartBodyFile?,<br>                                        _ request: inout URLRequest) {<br>        <br>        let body = NSMutableData()<br>            let boundary = generateBoundaryString()<br>            <br>            if let bodyParameters = bodyParameters {<br>                for (key, value) in bodyParameters {<br>                    body.append(&quot;--\(boundary)\r\n&quot;.data(using: String.Encoding.utf8)!)<br>                    body.append(&quot;Content-Disposition: form-data; name=\&quot;\(key)\&quot;\r\n\r\n&quot;.data(using: String.Encoding.utf8)!)<br>                    body.append(&quot;\(value)\r\n&quot;.data(using: String.Encoding.utf8)!)<br>                }<br>            }<br>        <br>       <br>        if let file = multiPartFile {<br>            body.append(&quot;--\(boundary)\r\n&quot;.data(using: String.Encoding.utf8)!)<br>            body.append(&quot;Content-Disposition:form-data; name=\&quot;\(file.fileName!)\&quot;; filename=\&quot;\(file.fileName!).png\&quot;\r\n&quot;.data(using: String.Encoding.utf8)!)<br>            body.append(&quot;Content-Type: \(file.fileMimeType!)\r\n\r\n&quot;.data(using: String.Encoding.utf8)!)<br>            body.append(file.fileData!)<br>            body.append(&quot;\r\n&quot;.data(using: String.Encoding.utf8)!)<br>        }<br>        <br>        body.append(&quot;--\(boundary)--\r\n&quot;.data(using: String.Encoding.utf8)!)<br>        request.setValue(&quot;multipart/form-data; boundary=\(boundary)&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>        request.httpBody = body as Data<br>        <br>    }<br>    <br>    <br>    fileprivate func generateBoundaryString() -&gt; String {<br>        return &quot;Boundary-\(NSUUID().uuidString)&quot;<br>    }<br>}</pre><p>This Swift file implements a generic networking layer using Combine framework for asynchronous programming, targeting iOS applications. It defines a protocol NetworkRouter with an associated type EndPoint, representing the endpoint type for network requests. The Router class conforms to this protocol and handles the construction and execution of network requests.</p><p>Key Components:</p><h4>Protocol NetworkRouter:</h4><ul><li>Defines a blueprint for network routers. It requires conforming types to implement a method request(_:) which initiates a network request with a specified endpoint and returns a Combine AnyPublisher emitting a tuple containing the response data and URL response or an error.</li></ul><h4>Class Router&lt;EndPoint: EndPointType&gt;:</h4><ul><li>Implements the NetworkRouter protocol with a generic type EndPoint.</li><li>Provides methods for building, configuring, and executing network requests using Combine framework’s Future and sink operators.</li><li>Handles different types of network tasks including simple requests, requests with parameters and headers, and requests with multipart data.</li><li>Manages cancellable subscriptions using the Set&lt;AnyCancellable&gt; property.</li></ul><h4>Helper Functions:</h4><ul><li>buildRequest(from:): Constructs a URLRequest based on the provided endpoint and its associated parameters.</li><li>configureParameters(bodyParameters:bodyEncoding:urlParameters:request:): Configures request parameters based on the specified encoding.</li><li>addAdditionalHeaders(_:request:): Adds additional HTTP headers to the request.</li><li>configureMultiPart(_:_:_:_:_): Configures multipart form data for the request.</li><li>generateBoundaryString(): Generates a boundary string for multipart form data.</li></ul><blockquote>The file encapsulates networking logic, abstracting away implementation details such as URLRequest construction, parameter encoding, and handling multipart data. It promotes modularity, flexibility, and testability in networking code for iOS applications built with Swift</blockquote><h3>12- HTTPClient</h3><pre>import Foundation<br>import Combine<br><br>public protocol HTTPClient {<br>    var cancellabels: Set&lt;AnyCancellable&gt; {get set}<br>    func sendRequest&lt;T:EndPointType, P:Codable&gt;(_ requestBuilder: T, model: P.Type) -&gt; AnyPublisher&lt;P, Swift.Error&gt;<br>}<br><br>extension HTTPClient {<br>    public consuming func sendRequest&lt;T:EndPointType, P:Codable&gt;(_ requestBuilder: T, model: P.Type) -&gt; AnyPublisher&lt;P, Swift.Error&gt; {<br>        return Future { promise in<br>            let router = Router&lt;T&gt;()<br>            do {<br>                router.request(requestBuilder)<br>                    .flatMap({ info -&gt;  AnyPublisher&lt;P, Swift.Error&gt; in<br>                        NetworkDecoder.handleNetworkResponse(info.1, info.0, model: model)<br>                    })<br>                    .sink { completion in<br>                        if case .failure = completion {<br>                            promise(.failure(NetworkDecoder.Error.failed))<br>                        }<br>                    } receiveValue: { val in<br>                        promise(.success(val))<br>                    }<br>                    .store(in: &amp;cancellabels)<br>            }<br>        }.eraseToAnyPublisher()<br>    }<br>}</pre><p>This Swift file defines a protocol HTTPClient representing a client for making HTTP requests. It includes a method sendRequest(_:model:) used for sending requests and receiving responses asynchronously. Additionally, it imports the Foundation and Combine frameworks.</p><p>Key Components:</p><h4>Protocol HTTPClient:</h4><ul><li>Declares requirements for objects capable of sending HTTP requests.</li><li>Includes a property cancellabels of type Set&lt;AnyCancellable&gt; used for managing Combine subscriptions.</li><li>Defines a method sendRequest(_:model:) that takes a request builder conforming to the EndPointType protocol and a model type conforming to Codable. It returns a publisher emitting the decoded response of type P or an error of type Swift.Error.</li></ul><h4>Extension HTTPClient:</h4><ul><li>Provides a default implementation of the sendRequest(_:model:) method.</li><li>Within this method:</li><li>It creates a Future publisher that takes a closure with a Promise parameter.</li><li>Inside the closure, it instantiates a Router with the provided request builder to initiate the request.</li><li>It then constructs a pipeline of Combine operators to handle the request:</li><li>Uses flatMap to handle the network response and decode it using NetworkDecoder.handleNetworkResponse.</li><li>Subscribes to the publisher returned by flatMap, handling completion and received values.</li><li>Stores the subscription in the cancellabels set for proper management.</li></ul><blockquote>This file encapsulates the functionality of sending HTTP requests asynchronously using Combine framework. The HTTPClient protocol provides a blueprint for implementing HTTP clients, while the extension offers a default implementation of the sendRequest(_:model:) method, promoting code reusability and adhering to the principles of protocol-oriented programming in Swift.</blockquote><h3>13- APIBuilder</h3><pre>import Foundation<br><br>public enum ApiBuilder {<br>    case getLeagues<br>    case getTeams(code: String)<br>    case getMatches(id: String)<br>}<br><br><br>extension ApiBuilder: EndPointType {<br>    <br>    <br>    var parameters: Parameters? {<br>        switch self {<br>        default:<br>            return nil<br>        }<br>    }<br>    <br>    public var headers: HTTPHeaders? {<br>        switch self {<br>        default:<br>            return defaultHeaders<br>        }<br>    }<br>    <br>    public var task: HTTPTask {<br>        switch self {<br>        default:<br>            return .requestParametersAndHeaders(bodyParameters: parameters, bodyEncoding: .jsonEncoding, urlParameters: nil, additionHeaders: headers)<br>        }<br>        <br>    }<br>    <br>    public var path: ServerPaths {<br>        switch self {<br>        case .getLeagues:<br>            return .leages<br>        case .getTeams:<br>            return .teams<br>        case .getMatches:<br>            return .matches<br>        }<br>    }<br>    <br>    public var pathArgs: [String]? {<br>        switch self {<br>        case .getLeagues:<br>            return nil<br>        case let .getTeams(code):<br>            return [code]<br>        case let .getMatches(id):<br>            return [id]<br>        }<br>    }<br>    <br>    public var httpMethod: HTTPMethod {<br>        switch self {<br>        default:<br>            return .get<br>        }<br>    }<br>}</pre><p>This Swift file defines an enumeration ApiBuilder that represents various API endpoints with associated parameters and configuration for making network requests. It also extends the ApiBuilder enum to conform to the EndPointType protocol, which defines the necessary properties and methods for constructing HTTP requests.</p><p>Key Components:</p><h4>Enum ApiBuilder:</h4><ul><li>Represents different API endpoints as cases of the enumeration.</li></ul><h4>Cases include:</h4><ul><li>getLeagues: Represents an endpoint for retrieving leagues.</li><li>getTeams: Represents an endpoint for retrieving teams, with a parameter for team code.</li><li>getMatches: Represents an endpoint for retrieving matches, with a parameter for match ID.</li><li>Provides computed properties and methods for configuring the request parameters, headers, task, path, path arguments, and HTTP method for each endpoint.</li></ul><h4>Extension ApiBuilder: EndPointType:</h4><ul><li>Extends the ApiBuilder enum to conform to the EndPointType protocol, which is used for constructing HTTP requests.</li><li>Implements the required properties and methods of the EndPointType protocol for each endpoint:</li><li>parameters: Returns the parameters for the request.</li><li>headers: Returns the headers for the request.</li><li>task: Returns the type of HTTP task to be performed (e.g., request with parameters and headers).</li><li>path: Returns the server path associated with the endpoint.</li><li>pathArgs: Returns any path arguments needed for the endpoint.</li><li>httpMethod: Returns the HTTP method for the request (e.g., GET, POST).</li></ul><blockquote>This file encapsulates the configuration of various API endpoints and their associated parameters, headers, and other details necessary for making network requests in an iOS application. The ApiBuilder enum provides a structured approach to defining and managing API endpoints, promoting code readability and maintainability.</blockquote><h3>Now let’s see how to Use it</h3><h3>14- BaseRepoLoader</h3><pre>import Foundation<br>import CombineNetworking<br>import Combine<br><br>public protocol BaseRepoLoader: HTTPClient {<br>    var cancellabels: Set&lt;AnyCancellable&gt; {get set}<br>    var callBackError: PassthroughSubject&lt;Bool,Error&gt; {get set}<br>    func ErrorHandler(_ completion: Subscribers.Completion&lt;Error&gt;)<br>}<br><br>extension BaseRepoLoader {<br>    public func ErrorHandler(_ completion: Subscribers.Completion&lt;Error&gt;) {<br>        if case let .failure(error) = completion {<br>            callBackError.send(completion: .failure(error))<br>        } else {<br>            callBackError.send(true)<br>        }<br>    }<br>}</pre><p>This Swift file defines a protocol BaseRepoLoader and extends it with default implementations using Combine framework. It also imports the Foundation framework and CombineNetworking module, and provides a protocol extension.</p><p>Key Components:</p><h4>Protocol BaseRepoLoader:</h4><ul><li>Declares requirements for objects capable of loading data from a remote server via HTTP requests.</li><li>Inherits from the HTTPClient protocol, which is presumably defined elsewhere in the CombineNetworking module or framework.</li><li>Defines properties and methods necessary for managing Combine subscriptions and error handling.</li></ul><h4>Protocol Extension:</h4><ul><li>Extends the BaseRepoLoader protocol with a default implementation for the ErrorHandler method.</li><li>The ErrorHandler method takes a completion object of type Subscribers.Completion&lt;Error&gt; as a parameter.</li><li>Inside the method, it checks if the completion is a failure, and if so, sends a failure completion event through the callBackError PassthroughSubject with the received error. Otherwise, it sends a success completion event with a boolean value of true.</li></ul><h4>Properties:</h4><ul><li>cancellabels: A set of AnyCancellable objects used to manage Combine subscriptions. Presumably, this set is intended to hold subscriptions made during network requests to allow for proper cancellation and memory management.</li><li>callBackError: A PassthroughSubject used for error handling. It emits either a success completion event with a boolean value of true or a failure completion event with an associated error when an error occurs during a network request.</li></ul><blockquote>This file provides a foundation for implementing networking-related functionality using Combine framework, allowing for modular and composable code for handling asynchronous operations and HTTP requests in Swift-based projects. It promotes reusability and encapsulation by defining a protocol that abstracts away common networking behaviors and provides default implementations for error handling.</blockquote><h3>15- RemoteLeagueItem -&gt; API Model</h3><pre>import Foundation<br><br>public struct RemoteLeagueItem: Codable {<br>    let competitions: [RemoteCompetition]<br>}<br><br>struct RemoteCompetition: Codable {<br>    let id: Int<br>    let area: Area<br>    let name, code: String<br>    let type: TypeEnum<br>    let emblem: String<br>    let plan: Plan<br>    let currentSeason: CurrentSeason<br>    let numberOfAvailableSeasons: Int<br>    let lastUpdated: String<br>}<br><br>// MARK: - Area<br>struct Area: Codable {<br>    let id: Int<br>    let name, code: String<br>    let flag: String?<br>}<br><br>// MARK: - CurrentSeason<br>struct CurrentSeason: Codable {<br>    let id: Int<br>    let startDate, endDate: String<br>    let currentMatchday: Int<br>}<br><br>enum Plan: String, Codable {<br>    case tierOne = &quot;TIER_ONE&quot;<br>}<br><br>enum TypeEnum: String, Codable {<br>    case cup = &quot;CUP&quot;<br>    case league = &quot;LEAGUE&quot;<br>}<br><br>// MARK: - Filters<br>struct Filters: Codable {<br>    let client: String<br>}</pre><h3>16- LeagueItem (Presentation model)</h3><pre>import Foundation<br><br>public struct LeagueItem: Equatable, Hashable {<br>    public let id: Int<br>    public let name: String<br>    public let logo: String<br>    public let code: String<br>    public let numberOfAvailableSeasons: Int<br>    <br>    public init(id: Int, name: String, logo: String, code: String, numberOfAvailableSeasons: Int) {<br>        self.id = id<br>        self.name = name<br>        self.logo = logo<br>        self.code = code<br>        self.numberOfAvailableSeasons = numberOfAvailableSeasons<br>    }<br>}</pre><h3>17- LeaguesLoader</h3><pre>public protocol LeaguesLoader: BaseRepoLoader {<br>    var AllLeagues: CurrentValueSubject&lt;[LeagueItem], Never&gt; { get }<br>    func load()<br>}<br><br>extension LeaguesLoader {<br>    public consuming func load() {<br>        sendRequest(ApiBuilder.getLeagues, model: RemoteLeagueItem.self)<br>            .receive(on: RunLoop.main)<br>            .map({$0.competitions.toModels()})<br>            .sink { completion in<br>                ErrorHandler(completion)<br>            } receiveValue: { val in<br>                AllLeagues.send(val)<br>            }.store(in: &amp;cancellabels)<br>    }<br>}<br><br>extension Array where Element == RemoteCompetition {<br>    func toModels() -&gt; [LeagueItem] {<br>        return self.map {LeagueItem(id: $0.id,<br>                                    name: $0.name,<br>                                    logo: $0.emblem,<br>                                    code: $0.code,<br>                                    numberOfAvailableSeasons: $0.numberOfAvailableSeasons)}<br>    }<br>}</pre><p>This Swift file defines a protocol LeaguesLoader that inherits from the BaseRepoLoader protocol and extends it with specific functionality related to loading leagues. Additionally, it provides an extension for the LeaguesLoader protocol with a default implementation for the load() method. The file also contains an extension on the Array type, providing a method toModels() to convert an array of RemoteCompetition objects to an array of LeagueItem objects.</p><p>Key Components:</p><h4>Protocol LeaguesLoader:</h4><ul><li>Inherits from the BaseRepoLoader protocol, inheriting its properties and methods related to HTTP requests and error handling.</li><li>Declares a property AllLeagues of type CurrentValueSubject&lt;[LeagueItem], Never&gt;, which is used to publish an array of LeagueItem objects.</li><li>Declares a method load() which is intended to initiate the loading of leagues data.</li></ul><h4>Protocol Extension:</h4><ul><li>Extends the LeaguesLoader protocol with a default implementation for the load() method.</li><li>Inside the load() method, it uses the sendRequest() method from the BaseRepoLoader protocol to initiate a network request to retrieve league data.</li><li>It then applies Combine operators to handle the received data and errors:</li><li>receive(on: RunLoop.main): Ensures that subsequent operators and subscribers are executed on the main thread.</li><li>map({...}): Maps the received RemoteCompetition objects to LeagueItem objects using the toModels() method defined in an extension on the Array type.</li><li>sink({...}): Subscribes to the publisher, handling completion and received values. It calls the ErrorHandler() method to handle any errors, and if successful, it publishes the received LeagueItem objects to the AllLeagues subject.</li></ul><h4>Extension on Array:</h4><ul><li>Extends the Array type where the element is RemoteCompetition.</li><li>Defines a method toModels() which converts an array of RemoteCompetition objects to an array of LeagueItem objects by mapping their properties accordingly.</li></ul><blockquote>This file encapsulates the functionality related to loading leagues data from a remote server. It provides a protocol for defining the behavior of a leagues loader and implements default functionality for initiating the loading process. Additionally, it includes an extension to convert data received from the server into a format suitable for the application’s model layer.</blockquote><h3>18- BaseViewModel</h3><pre>import Foundation<br>import SwiftUI<br>import Combine<br>import protocol LeagueFeature.BaseRepoLoader<br><br>enum DataStates {<br>    case loading<br>    case finished(Outcome)<br>        <br>    enum Outcome {<br>        case success<br>    }<br>}<br><br>typealias DataState =  Result&lt;DataStates, Error&gt;<br><br><br>class BaseViewModel: ObservableObject, BaseRepoLoader{<br>    <br>    var cancellabels = Set&lt;AnyCancellable&gt;()<br>    var callBackError = PassthroughSubject&lt;Bool, Error&gt;()<br>    <br>    <br>    @Published var dataStatus: DataState?{<br>        didSet {<br>            switch dataStatus{<br>            case let .failure(err):<br>                presentableError = err.localizedDescription<br>                showAlert = .constant(true)<br>                if isLoading.wrappedValue == true {<br>                    isLoading = .constant(false)<br>                }<br>            case let .success(value):<br>                switch value {<br>                case .loading:<br>                    isLoading = .constant(true)<br>                case let . finished(Outcome):<br>                    isLoading = .constant(false)<br>                    switch Outcome {<br>                    case .success:<br>                        presentableError = &quot;&quot;<br>                        showAlert = .constant(false)<br>                    }<br>                }<br>            default:<br>                break<br>            }<br>        }<br>    }<br>    <br>    var isLoading: Binding&lt;Bool&gt; = .constant(false)<br>    var showAlert: Binding&lt;Bool&gt; = .constant(false)<br>    var presentableError = &quot;&quot;<br>    <br>    let defaultError = NSError(domain: &quot;SomeThing went wrong please try again later&quot;, code: 0)<br>    <br>    init() {<br>        callBackError<br>            .receive(on: RunLoop.main)<br>            .sink { completion in<br>                if case let .failure(error) = completion {<br>                    self.dataStatus = .failure(error)<br>                }<br>            } receiveValue: { val in<br>                self.dataStatus = .success(.finished(.success))<br>            }.store(in: &amp;cancellabels)<br>    }<br>}</pre><p>This Swift file defines a base view model BaseViewModel intended for use in SwiftUI applications. The view model conforms to the ObservableObject protocol, making it suitable for use with SwiftUI&#39;s @Published property wrapper for reactive UI updates. Additionally, it implements the BaseRepoLoader protocol, inheriting its properties and methods related to network requests and error handling.</p><p>Key Components:</p><h4>Class BaseViewModel:</h4><ul><li>Inherits from ObservableObject and implements BaseRepoLoader.</li><li>Contains properties for managing the state of data loading (dataStatus), loading indicator (isLoading), error presentation (showAlert and presentableError), and a default error (defaultError) to be used when an error occurs.</li><li>Defines a typealias DataState as a Result type with possible states of loading or finished with an associated Outcome.</li><li>Implements a method uiUpdate(when:) to perform UI updates on the main thread asynchronously.</li><li>Provides an initializer to set up Combine subscriptions for error handling via callBackError. When an error occurs, it updates the dataStatus property accordingly.</li></ul><h4>Enum DataStates:</h4><ul><li>Defines possible states for the dataStatus property, including loading and finished with an associated Outcome.</li></ul><h4>Extensions:</h4><ul><li>Extends DataStates.Outcome with a case success.</li></ul><h4>Typealiases:</h4><ul><li>Defines a typealias DataState as a Result type representing the state of data loading operations.</li></ul><blockquote>This file serves as a foundation for creating view models in SwiftUI applications that require asynchronous data loading and error handling. It encapsulates common functionality related to managing data loading states, error presentation, and UI updates in a reactive and modular manner using Combine framework and SwiftUI’s data flow principles.</blockquote><h3>19- LoaderModifier</h3><pre>import Foundation<br>import SwiftUI<br>struct LoaderModifier: ViewModifier {<br>    <br>    @Binding var showLoader: Bool<br>    <br>    func body(content: Content) -&gt; some View {<br>        ZStack {<br>            content<br>                .disabled(showLoader)<br>            ProgressView(&quot;&quot;)<br>                .progressViewStyle(CircularProgressViewStyle())<br>                .opacity(showLoader ? 1 : 0)<br>                .animation(.linear(duration: 0.5), value: showLoader)<br>        }<br>    }<br>}<br><br>extension View {<br>    func LoadingConfig(show: Binding&lt;Bool&gt;) -&gt; some View {<br>        self.modifier(LoaderModifier(showLoader: show))<br>    }<br>}</pre><h3>20- ViewModel</h3><pre>import Foundation<br>import Combine<br>import protocol LeagueFeature.LeaguesLoader<br>import struct LeagueFeature.LeagueItem<br><br>class ContentViewModel: BaseViewModel, LeaguesLoader {<br>    <br>    private(set) var AllLeagues = CurrentValueSubject&lt;[LeagueItem], Never&gt;([])<br>    <br>    override init() {<br>        super.init()<br>        fetchAllLeagues()<br>    }<br>    <br>    func fetchAllLeagues() {<br>        dataStatus = .success(.loading)<br>        self.load()<br>    }<br>}</pre><h3>21- View</h3><pre>import SwiftUI<br>import struct LeagueFeature.LeagueItem<br>import Combine<br><br>struct ContentView: View {<br>    let vm = ContentViewModel()<br>    @State var leage = [LeagueItem]()<br>    var body: some View {<br>        VStack {<br>            Text(leage.count &gt; 0 ? &quot;Data Fetched \(leage.count)&quot; : &quot;No Data Yet&quot;)<br>        }<br>        .padding()<br>        .LoadingConfig(show: vm.isLoading)<br>        .alert(vm.presentableError, isPresented: vm.showAlert) {<br>            Button(&quot;OK&quot;, role: .cancel) { }<br>        }<br>        .onReceive(vm.AllLeagues, perform: { value in<br>            leage = value<br>        })<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b54780719099" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>