Network

DigitalblendKit provides Network Sub Component to manage network related tasks.

Instalation

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler. It is in early development, but Alamofire does support its use on supported platforms.

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

dependencies: [
    .package(url: "http://git.digitalblend.lan/Framework/DigitalblendKit-swift.git")
]

Usage

For the test purpose of this getting started let’s work with JSONTest

Import

import Digitalblend

Configure

Configure the Route enumeration to describes API endpoints.

enum JSONTestRoute: Route {
    case echoParameters

    var infos: Infos {
        switch self {
        case .echoParameters: return (url: "http://echo.jsontest.com/", method: .get
        }
    }

}

Configure the API endpoint response struct, with Decodable compliance for the deserialization.

private struct JSONTestParametersResponse: Decodable {
    var Key: String
}

Making requests

First you need to instenciate a Router with the Route type.

let router = Router<JSONTestRoute>()

Now you can work with your API endpoints. The code below is an example of how to create request, track progress and handle the completion status.

router
.request(.echoParameters)
.progression { fractionCompleted in
    print(fractionCompleted)
}
.completion { result in
    switch result {
    case .success(let response, let data):
        print(response) // response: URLHTTPResponse
        print(data) // data: Data
    case .failure(let error):
        print(error) // error: Error
    }
}

The code below show you how to build request with parameters and deserialize data into given type.

let parameters = ["Key": "Value", ]

router
.request(.echoParameters)
.build(parameters: parameters, encoder: URLRESTParametersEncoder.default)
.completion(JSONTestParametersResponse.self) { result in
    switch result {
    case .success(let response, let data): 
        print(response) // response: URLHTTPResponse 
        print(data) // data: JSONTestParametersResponse
    case .failure(let error): 
        print(error) // error: Error
    }
}

Making downloads

Router can also download, basically it is the same behaviour as request with :

  • The completion result will contain the HTTPURLResponse object as usual
  • The completion result will contain an URL object
  • You can’t deserialize the data cause by typing completion method
router
.download(.echoParameters)
.completion { result in
    switch result {
    case .success(let response, let url):
        print(response) // response: URLHTTPResponse
        print(url) // url: URL
    case .failure(let error): // error: Error
        print(error)
    }
}

Making uploads

`Coming...`

Todo

  • [ ] Upload Task management in Router.