Astral
Astral is a minimal HTTP Networking library that aims to simplify an application's networking layer by abstracting the steps needed to create a network request into multiple objects.
It aims to shy away from the typical network layer singleton by encapsulating each part of network request as an object.
Astral makes use of the BrightFutures library to flatten the asynchronous calls associated with networking, making your code base as readable as possible.
Inspired by Soroush Khanlou's blog post on Protocol Oriented Programming.
Requirements
Astral requires iOS 10.0 or higher and Swift 3.x
Installation
CocoaPods
- Add the following to your Podfile:
pod 'Astral'
- Integrate your dependencies using frameworks: add
use_frameworks!
to your Podfile. - Run
pod install
.
Example
Here's an example using the Pokemon API
struct PokeAPIConfiguration: Configuration {
var scheme: URLScheme {
return URLScheme.http
}
var host: String {
return "pokeapi.co"
}
var basePathComponents: [String] {
return [
"api",
"v2"
]
}
var baseHeaders: [String : Any] {
return [
"Content-Type": "application/json"
]
}
}
struct PokemonRequest: Request {
let id: Int
var configuration: Configuration {
return PokeAPIConfiguration()
}
var pathComponents: [String] {
return [
"pokemon",
"\(self.id)"
]
}
var method: HTTPMethod {
return HTTPMethod.GET
}
var parameters: [String : Any] {
return [:]
}
var headers: [String : Any] {
return [:]
}
}
let queue: DispatchQueue = DispatchQueue(label: "pokeapi", qos: DispatchQoS.userInitiated, attributes: [DispatchQueue.Attributes.concurrent])
let request: Request = PokemonRequest(id: 1)
let dispatcher: RequestDispatcher = JSONRequestDispatcher(
request: request, builderType: JSONRequestBuilder.self, printsResponse: true
)
dispatcher.dispatchURLRequest()
.onSuccess(queue.context) { (data: Data) -> Void in
// Create and parse JSON
}
.onFailure(queue.context) { (error: NetworkingError) -> Void in
// Handle the error
}
.onComplete(queue.context) { (result: Result<Data, NetworkingError>) -> Void in
// Handle the completion of the network request
// such as clean up of the UI
}
Author
License
Astral is available under the MIT license. See the LICENSE file for more info.