Protocol oriented networking layer on top of Alamofire
- Alamofire: Elegant HTTP Networking in Swift.
- Google/Promises: a modern framework that provides a synchronization construct for Objective-C and Swift to facilitate writing asynchronous code.
1. Entities:
Responses
struct Book: Decodable {
var id: String
var title: String
var author: String
var releaseDate: Date?
var pages: Int
}
struct VoidResponse: Decodable {
// Some endpoints might return: 204 No Content
}
Parameters
struct AddBookParameters: Encodable {
var title: String
var author: String
var releaseDate: Date?
var pages: Int
}
2. UseCase:
protocol BooksUseCase {
func loadBooks() -> Promise<[Book]>
func addBook(_ parameters: AddBookParameters) -> Promise<Book>
func deleteBook(_ book: Book) -> Promise<VoidResponse>
}
final class APIBooksUseCase {
private let apiClient: APIClient
// Automatic configurations
init(apiClient: APIClient = DefaultAPIClient()) {
self.apiClient = apiClient
}
}
extension APIBooksUseCase: BooksUseCase {
func loadBooks() -> Promise<[Book]> {
let request = RequestBuilder<[Book]>()
.path("books")
.method(.get)
.build()
return apiClient.execute(request)
}
func addBook(_ parameters: AddBookParameters) -> Promise<Book> {
let request = RequestBuilder<Book>()
.path("books")
.method(.post)
.encode(parameters, bodyEncoding: .jsonEncoding)
.build()
return apiClient.execute(request)
}
func deleteBook(_ book: Book) -> Promise<VoidResponse> {
let request = RequestBuilder<VoidResponse>()
.path("books/\(book.id)")
.method(.delete)
.build()
return apiClient.execute(request)
}
}
CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate CoreNetwork into your Xcode project using CocoaPods, specify it in your Podfile
:
pod 'CoreNetwork', :git => "https://github.com/AnasAlhasani/CoreNetwork"
Then, run the following command:
$ pod install
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 CoreNetwork as a dependency is as easy as adding it to the dependencies
value of your Package.swift
.
dependencies: [
.package(url: "https://github.com/AnasAlhasani/CoreNetwork.git", from: "v1.0.7")
]
Anas Alhasani