A lightweight swift network layer with Combine, Async-Await, and a traditional completion block.

Overview

CombineNetwork

A simple light-weight network library to make network requesting simpler. It supports newer techonology such as async/await as well as traditional completion block.

How to install

Follow the tutorial provided by Apple to install this library as a package: https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app

How to use

Library allows to decode a structure or class while performing a network request. In order to make a network request either use Request class or extend RequestTask class for custom request.

Decodable

In order for the client to decode an object, it should implement the protocol SelfDecodable like:

struct MyCustomDecodable: SelfDecodable {
    let id: Int
    let name: String
    let age: String

    // Either use default decoder or create custom
    static var decoder: JSONDecoder = .default
}

Request

To perform a request you can use one of the following functions:

Swift Combine:

func performRequest<Value: SelfDecodable>(_ request: RequestTask) -> AnyPublisher<Value, Error>

Swift Async/Await:

func performRequest<Value: SelfDecodable>(_ request: RequestTask) async throws -> Value

Completion block:

func performRequest<Value: SelfDecodable>(_ request: RequestTask, completion: @escaping ResultCompletion<Value>)

In each of the above function Value represents the Decodable response class.

Example:

Response object:

struct TestDecodable: SelfDecodable {
    static var decoder: JSONDecoder = {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        return decoder
    }()
    
    let  firstName: String
    let  lastName: String
}

Request:

let host = URLHost(rawValue: "myshop.com")
let endpoint = Endpoint(path: "/items/42")
let request = Request(host: host, endpoint: endpoint)
let response: TestDecodable = try await NetworkClient.shared.performRequest(request)

Suggestions

Default URL base host:

While Request allows to change request host, scheme and other information before the call is initiated, you might wanna have a global standard host. For that extend URLHost

extension URLHost {
    static var `default`: Self {
        return URLHost(rawValue: "myshop.com")
    }
}

let endpoint = Endpoint(url: "/items/42")
let request = Request(host: .default, endpoint: endpoint)

Endpoints structure:

For better readability of endpoints, you might wanna extend the Endpoint struct to create readable paths.

extension Endpoint {
    static func getAllItems(offset: Int, limit: Int): Self {
        return Endpoint(path: "/api/v2/items", queryParameters: [
            URLQueryItem(name: "limit", value: String(limit)),
            URLQueryItem(name: "offset", value: String(offset))
        ])
    }
}
let endpoint = Endpoint.getAllItems(offset: 0, limit: 20)
let request = Request(host: .default, endpoint: endpoint)
You might also like...
Example project showing how to use async/await with iOS 13
Example project showing how to use async/await with iOS 13

ios13AsyncAwait Example project showing how to use async/await with iOS 13 Article This source code is a part of an article published at This Dev Brai

Using async / await on iOS 13: everything you need to know
Using async / await on iOS 13: everything you need to know

Using async / await on iOS 13: everything you need to know! 🚀 Content This repository contains the code sample I've used during December 14th's lives

iOS 13-compatible backports of commonly used async/await-based system APIs that are only available from iOS 15 by default.

AsyncCompatibilityKit Welcome to AsyncCompatibilityKit, a lightweight Swift package that adds iOS 13-compatible backports of commonly used async/await

AsyncTaskKit - contains some additions to async/await Task

AsyncTaskKit This repo contains some additions to async/await Task. In general i

A demonstration for bridging between Combine and your new async functions

CombineAsyncually This is a DEMONSTRATION of how you can bridge the new async / await functionality in Swift 5.5 with Combine. There is NO WARRANTY. T

AsyncExtensions aims to mimic Swift Combine operators for async sequences.

AsyncExtensions AsyncExtensions provides a collection of operators, async sequences and async streams that mimics Combine behaviour. The purpose is to

Async and concurrent versions of Swift’s forEach, map, flatMap, and compactMap APIs.

CollectionConcurrencyKit Welcome to CollectionConcurrencyKit, a lightweight Swift package that adds asynchronous and concurrent versions of the standa

⚡️ Fast async task based Swift framework with focus on type safety, concurrency and multi threading
⚡️ Fast async task based Swift framework with focus on type safety, concurrency and multi threading

Our apps constantly do work. The faster you react to user input and produce an output, the more likely is that the user will continue to use your appl

Swift TableView pagination with async API request.
Swift TableView pagination with async API request.

SwiftTableViewPagination Swift TableView pagination with async API request. Output UML Create puml file. $ cd SwiftTableViewPagination/scripts/swiftum

Comments
Releases(0.0.1)
  • 0.0.1(Oct 4, 2021)

Owner
Dushant Singh
iOS Developer
Dushant Singh
A Swift lib for network with async/await

SmileNetwork A Swift network utility with async/await applied UseAge enum MockEndpoint { case weather(cityId: String) } extension MockEndpoint: S

null 2 Jul 13, 2022
Test app for the InStat company. The project uses MVVM architecture, interface created with SwiftUI, network requests with async/await

FootStats Test app for the InStat company. The Project uses MVVM architecture, interface created with SwiftUI, network requests with async/await using

Nizami Tagiyev 4 Dec 15, 2022
Hydra ⚡️ Lightweight full-featured Promises, Async & Await Library in Swift

Lightweight full-featured Promises, Async & Await Library in Swift What's this? Hydra is full-featured lightweight library which allows you to write b

Daniele Margutti 2k Dec 24, 2022
Hydra: Lightweight full-featured Promises, Async-Await Library in Swift

Async Functions for ECMAScript The introduction of Promises and Generators in EC

Ecma TC39 1.6k Oct 17, 2022
Lightweight async/await networking library with interceptor support - usable from iOS 13+.

Lightweight async/await networking library with interceptor support. ?? Getting started AsyncNetwork's session acts as a wrapper to URLSession by addi

Paul 9 Oct 4, 2022
straightforward networking and error handling with async-await and URLSession

AsyncAwaitNetworkingPlayground How To Run Just clone the project, open it and run. Some notes about AsyncAwaitNetworkingPlayground It's a straightforw

Fırat Yenidünya 17 Dec 11, 2022
Edit images and video with async / await in Swift, powered by Metal.

AsyncGraphics The core value type in AsyncGraphics is a Graphic. It's like an image, tho it can be used with various async methods. Documentation Swif

Anton Heestand 33 Dec 27, 2022
⏳ Collection of Swift 5.5 async/await utility functions.

⏳ FunAsync Collection of Swift 5.5 async/await utility functions. Throw <-> Result conversion asyncThrowsToAsyncResult asyncResultToAsyncThrows More C

Yasuhiro Inami 23 Oct 14, 2022
🎭 Swift async/await & Actor-powered effectful state-management framework.

?? Actomaton ??‍?? Actor + ?? Automaton = ?? Actomaton Actomaton is Swift async/await & Actor-powered effectful state-management framework inspired by

Yasuhiro Inami 199 Dec 20, 2022
AsyncLocationKit - Async/await CoreLocation With Swift

AsyncLocationKit Wrapper for Apple CoreLocation framework with new Concurency Mo

AsyncSwift 89 Dec 30, 2022