Code Challenge - Using Alamofire is a Swift-based, HTTP networking library, also Codable for Data Model and Combine Framework .

Overview

Code Challenge

##Using Alamofire is a Swift-based, HTTP networking library, also Codable for Data Model and Combine Framework .

Alamofire is one of the most popular and widely used Swift networking libraries. Built on Apple’s Foundation networking stack, it provides an elegant API to make network requests. With over thirty-thousand stars on GitHub, it’s one of the top-rated Swift repositories. Codable is a type alias for the Encodable and Decodable protocols. When you use Codable as a type or a generic constraint, it matches any type that conforms to both protocols.

I using a Model-View-ViewModel (MVVM) is a software design pattern that is structured to separate program logic and user interface controls.

The pattern is often used in Windows and web graphics presentation software. design patterns MVVM

Code Architecture :

1- Create Network Layer with Protocol and Generic in separate layer .

2- Use Model-View-ViewModel design pattern to make request to server and binding to ViewController .

3- To prevent duplication of code , I try to using the same view controller to used it again .

4- Using of Cell Reuse Extensions .

Example of code

this method is make HTTP request and get response by Alamofire and It handle the response with Future publisher from Combine Framework

public static func NetworkRequest
   
    (url: URLRequestConvertible) -> Future
    
      where T : Decodable {
    return Future
     
       { promise in
        AF.request(url).decodable { data in
            promise(.success(data))
        } failure: { (error) in
            promise(.failure(error!))
        }
    }
 }

     
    
   

Loading data from Network layer to ViewModel : here I return data from newtork layer and change state for enumeration depend on response

 private func loadDataFromServer(manufacturerKey: String = "" ,page:Int) {
   if isConnected {
     let networkRequest = manufacturerKey.isEmpty ?  NetworkRequestLayer.loadData(page:"\(self.page)", pageSize:"\(pageSize)") 
                                                   : NetworkRequestLayer.loadData(manufacturerID:manufacturerKey,page: "\(page)", pageSize: "\(pageSize)")
        let cancellable = networkRequest.sink(receiveCompletion: { (result) in
            switch result {
            case .failure(let error):
                if let errorMsg = "\(error.localizedDescription)" as String? {
                    self.state = .error(errorMsg)
                }
                break
            case .finished:
                break
            }
        }, receiveValue: { (result) in
            if let data =  result.wkda {
                if let totalPageCount = result.totalPageCount{
                    self.totalPageCount = totalPageCount
                    data.forEach { (k,v) in  self.dataSource[k] = v }
                    self.state = .loaded
                }else{
                    self.state = .error("No Data in api")
                }
                
            }else{
                self.state = .error("No Data in api")
            }
        })
        self.subscriptions.insert(cancellable)
    }else{
        self.state = .noInternet("No internet Connection Please check for internet settings")
    }
}

binding Data from View Model to View Controller

    self.vm.$state.sink { (state) in
        switch state {
        case .noInternet(let noInternetMsg):
            //main screen thread to update UI after loading
            DispatchQueue.main.async {
                Spinner.dissmiss()  // if no internet connection , you have to dismiss spinner
                // show No internet connection of alert
                Util.showAlert(caller: self, title: "Message", message: "\(noInternetMsg)")
            }
            break
        case .idle:
            Spinner.start() // start spinner animation
            break
        case .loading:
            Spinner.dissmiss()
            break
        case .loaded:
            //main screen thread to update UI after loading
            DispatchQueue.main.async {
                Spinner.dissmiss() // if finish loading,you have to dismiss spinner
                self.reloadTableView() // reload tableview again
            }
            break
        case .error(let error):
            //main screen thread to update UI after loading
            DispatchQueue.main.async {
                Spinner.dissmiss()  // if error was happen , you have to dismiss spinner
                // show error of alert
                Util.showAlert(caller: self, title: "Message", message: "\(error)")
            }
            break
        }
    }.store(in: &cancellables)
You might also like...
WWDC2020 Swift Student Challenge - TheHackOfRayTracing playground book
WWDC2020 Swift Student Challenge - TheHackOfRayTracing playground book

wwdc2021 My wwdc2021 submission The HackOf RayTracing How to run Install swift playground from App Store on your Mac or iPad Double clik TheHackOfRayT

[Accepted] My WWDC2021 Swift Student Challenge submission chosen as one of the 350 winners!
[Accepted] My WWDC2021 Swift Student Challenge submission chosen as one of the 350 winners!

Genetic Algorithms | WWDC21 This project was entirely built with SwiftUI. To direct download this Playground and run it on your Mac or IPad, click he

My Winning Submission for Apple's WWDC 2021 Swift Student Challenge
My Winning Submission for Apple's WWDC 2021 Swift Student Challenge

Symmetries This playground book gives a quick insight into the symmetry groups of 3-dimensional objects like the platonic solids. The user can play ar

The Feed API challenge with swift
The Feed API challenge with swift

The Feed API challenge - iOSLeadEssentials.com It's time to put your skills to the test! You are called to implement the RemoteFeedLoader to load a co

My winning contribution to Apple's Swift Student Challenge 2021

SynthApp My winning contribution to Apple's Swift Student Challenge 2021 This repository contains an Xcode project and the final Swift Playgrounds fil

Challenge-vip-delivery - Project for VIP (Clean Swift) Architecture Dev Sprints on Devpass
Challenge-vip-delivery - Project for VIP (Clean Swift) Architecture Dev Sprints on Devpass

VIP (Clean Swift) - Delivery App 🍕 Neste desafio, aplicaremos conceitos da arquitetura VIP para finalizar a implementação de um aplicativo. Desenvolv

'The Particle Binder' - Winning WWDC22 Swift Student Challenge submission!

The Particle Binder 'The Particle Binder' - Winning WWDC22 Swift Student Challenge submission! Welcome to The Particle Binder, the particle accelerato

Swift client for Software-Challenge Germany 2022/2023

Swift client for Software-Challenge Germany 2022/2023 This package contains a simple client written in Swift for Software-Challenge Germany 2022/2023.

Task App for Swift that Persist Data with Core Data (iOS)
Task App for Swift that Persist Data with Core Data (iOS)

Originally by: Michael Crump Updates for Xcode 10 with Swift 4.2 by David Phillip Oster

Owner
Eng Angelo Saber
X-code Man that is my nick name , Senior IOS Developer , PHP Web-developer , I love coding every time ,Simplicity is the soul of efficiency.
Eng Angelo Saber
iOS Tech Challenge - Take Home Challenge

iOS Tech Challenge - Take Home Challenge Thank you for your interest in taking the iOS Tech Challenge. Preparation Please, compile the project in Xcod

null 0 Oct 18, 2021
Challenge-M2Y-TM4 - A challenge provided by Mobile2You, with the purpose of analyzing knowledge about UI, API consumption

Challenge-M2Y-TM4 Um desafio proporcionado pela Mobile2You, com proposito de ana

Felipe Brigagão de Almeida 0 Jan 31, 2022
TakeHomeChallenge - iOS Tech Challenge - Take Home Challenge

iOS Tech Challenge - Take Home Challenge Thank you for your interest in taking t

Michael 0 Feb 1, 2022
iOS NBA Challenge Based on Xcode 12.4, PR2S Project By: Oscar Pastás

iOS NBA Challenge Based on Xcode 12.4, PR2S Project By: Oscar Pastás iOS This test app consists of a list of users Considerations This test should be

null 0 Nov 26, 2021
Starter project for the iOS code challenge

iOS Base Project for Podium Take-Home Challenge Introduction We have provided two version of this base project: one using UIKit, one using SwiftUI. Th

Podium 1 Dec 29, 2021
Code challenge iOS - Movies app

Code challenge iOS - Movies app Project structure The Common folder contains sha

Danny Narvaez 0 Dec 21, 2021
Example on how to print a NSTableView from your app but then also add text to the print-out.

NSTableView Printing Test This is a demo project so you can check out how printing a table could work. The goal here is to show tabular data on screen

Clean Cocoa 3 Mar 29, 2022
🎉 WWDC 2021 Swift Student Challenge Winner 🎉 Dance Party allows users to record choreography and play against other users to try and match the key poses!

?? Dance Party ?? ?? WWDC 2021 Swift Student Challenge Winner ?? Installation Steps (Works on iPad Only) Clone or Download Unzip the .playgroundbook.z

Alan Yan 7 Oct 17, 2022
Rick and Morty Challenge With Swift

Rick-and-Morty-Challenge A Branch mais atualizada é a main. Tecnologias Modo cla

Felipe Brigagão de Almeida 0 Feb 8, 2022
[Accepted] My WWDC21 Swift Student Challenge submission

My WWDC21 Swift Student Challenge submission I made a playground book that teaches you the basics of ARKit through interactive lessons. It covers posi

Zheng 25 Nov 12, 2022