a lightweight, flexible, and easy to use networking abstraction layer for making http requests
- in xcode, select “file” → “add packages...”
- enter https://github.com/akxo/apikit
add the pod to your podfile
pod 'api-kit'
install pod
pod install
import the module
import APIKit
create the api client with your baseurl
let clientBuilder = APIClientBuilder(baseUrl: "your-base-url-here")
let client = clientBuilder.build()
there are 3 methods for making network requests depending on your preference:
- completion handler
func load<T>(resource: Resource<T>, completion: @escaping (Result<T, Error>) -> Void)
- combine
func load<T>(resource: Resource<T>) -> AnyPublisher<T, Error>
- async/await
func load<T>(resource: Resource<T>) async -> Result<T, Error>
create response object (make sure it's decodable)
struct APIMovie: Decodable {
let title: String
let director: String
}
build resource
let resource = Resource<[APIMovie]>(
jsonDecoder: JSONDecoder(),
path: "/movies",
method: .get,
params: ["upcoming": true]
)
make the request
client.load(resource: resource) { result in
switch result {
case let .success(movies):
// handle movies
case let .failure(error):
// handle error
}
}
client.load(resource: resource)
.sink { completion in
switch completion {
case .finished:
// handle completion
case let .failure(error):
// handle error
}
} receiveValue: { movies in
// handle movies
}
let result = await client.load(resource: resource)
switch result {
case let .success(movies):
// handle movies
case let .failure(error):
// handle error
}
build resource
let resource = Resource<APIMovie>(
jsonDecoder: JSONDecoder(),
path: "/movies",
method: .post,
params: [
"title": "inception",
"director": "christopher nolan"
]
)
make the request like above