Skip to content

Repository files navigation

NetworkEngine

Swift 5.0 Swift Package Manager

Network engine is the networking framework on top of Alamofire, for simplified and testable network. It supports combine (publishers pattern) and async await

Installation

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.

Once you have your Swift package set up, adding NetworkEngine as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/SimformSolutionsPvtLtd/NetworkEngine.git", .upToNextMajor(from: "2.1.0"))
]

Note: This is a private repository (SimformSolutionsPvtLtd/NetworkEngine), so it is accessible only via GitHub login. Make sure you're authenticated with a GitHub account that has access before adding it as a package dependency.

Usage

TargetType: Define the network repository

Confirm to TargetType protocol and define your network repo as below, based on your requirements you can define multiple repos same as this one.

protocol NetworkRepo: TargetType & NetworkRequestable {
    static var refreshToken: Self { get }
    static func login(email: String, password: String) -> Self
    static func demo(demoData: DemoRequestModel) -> Self
    static func fetchUsers(userListRequest: UserListRequest) -> Self
}

where NetworkRequestable defines the available methods for network calls

protocol NetworkRequestable {

    func request<T: Decodable>(type: T.Type,
                               callback: @escaping (Result<T, CustomError>) -> Void) -> NetworkRequest
}

Implement the NetworkRepo and define the required variables and methods using enum with example name APITarget.

public enum APITarget: NetworkRepo {
    case refreshToken
    case login(email: String, password: String)
    case demo(demoData: DemoRequestModel)
    case fetchUsers(userListRequest: UserListRequest)
}

NetworkProvider: Make the network calls

For the network calls in request method of the NetworkRequestable, create NetworkProvider instance

static let interceptor = DefaultInterceptor(refreshTokenCall)
static let provider = NetworkProvider<APITarget>(interceptor: interceptor)

where the DefaultInterceptor is the default interceptor initialized with refreshTokenCall closure.

The network provider also has methods to get the request tasks based on the request you want to make

  • StringRequestTask
  • DataRequestTask
  • DecodableRequestTask
  • UploadTask
  • DownloadTask

And then you can call the appropriate methods based on how you want the result. i.e. in the form of callback, publisher or async.

NetworkRequestInterceptor: Intercept the network calls

Define your own interceptor using NetworkRequestInterceptor. Define retry, adapt methods then pass your custom interceptor to the NetworkProvider

NetworkTask

The NetworkTask defines how you can request the data/files.

case requestPlain

This network task just requests the plain URL formed via basURl and path components of NetworkTask

case requestData(Data)

This task forms an HTTP request with the given Data in body of the request.

case requestJSONEncodable(Encodable)

This task forms and HTTP request by encoding the given Encodable using JSONEncoder and add setting the encoded data as request body.

case requestCustomJSONEncodable(Encodable, encoder: JSONEncoder)

This task does the same as above one, only difference is that it uses the provided encoder. Use this task if your request body needs some unconventional encoding and you need to handle it yourself by providing you preconfigured encoder.

case requestParameterEncodable(Encodable)

This task converts the given Encodable as key value dictionary and passes them as query string for the URL formation.

case requestParameters(parameters: [String: Any], encoding: ParameterEncoding)

Queries the given parameters using given ParameterEncoding method.

case requestCompositeData(bodyData: Data, urlParameters: [String: Any])

Set the given url parameters and body data in request.

case requestCompositeParameters(bodyParameters: [String: Any], urlParameters: [String: Any])

Encode the body parameters in to body of the request and append the url parameter in to query string of URL

case uploadFile(URL)

Upload the file at the given URL to the destination endpoint

case uploadMultipart([MultipartFormData])

Upload the multipart from data

case uploadCompositeMultipart([MultipartFormData], urlParameters: [String: Any])

Upload the multiple form data

case downloadDestination(DownloadDestination)

Download the data using given download destination

case downloadParameters(parameters: [String: Any],
                        encoding: ParameterEncoding,
                        destination: DownloadDestination)

Form a download request using given parameters and download the data using given download destination

Errors

Errors are thrown in form of NetworkError.

case networkError(_ error: AFError, _ response: HTTPURLResponse?, _ data: Data?)

This error is a wrapper on error thrown from Alamofire side with additional info

case encodableParameterFailure(error: Error)

Thrown when NetworkTask.requestParameterEncodable fails to encode the given encodable in to request parameters.

case jsonDictionaryConversionFailed

Json to Dictionary conversion failed for URL parameter encoding

License

MIT License

Copyright (c) 2023 Simform Solutions

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages