adaptRequest method is called before making a request allowing you to transform it adding headers, changing path, …
rescueRequestError is called whenever the request fail. You’ll have a chance to retry the request. This can be used to re-authenticate the user for instance
SimpleHTTP
Make HTTP API calls easier. Built on top of URLSession.
Installation
Use Swift Package Manager to install the library:
The package come with 2 modules:
SimpleHTTPwhich bring the full framework API described in this READMESimpleHTTPFoundationwhich only bring a few addition to Foundation API. See this article or API doc to have a glimpse of what is provided.Basic Usage
Building a request
You make requests by creating
Requestobjects. You can either create them manually or provide static definition by extendingRequest:This defines a
Request.login(_:)method which create a request targeting “login” path by sending aUserBodyand expecting aUserResponseas response.Sending a request
You can use your request along
URLSessionby converting it into aURLRequestby callingrequest.toURLRequest(encoder:relativeTo:accepting).You can also use a
Sessionobject.Sessionis somewhat similar toURLSessionbut providing additional functionalities:A few words about Session:
baseURLwill be prepended to all call pathsURLSessioninstance if ever neededSend a body
Request support two body types:
Encodable
To send an Encodable object just set it as your Request body:
Multipart
You can create multipart content from two kind of content
URL)Data)First example show how to create a request sending an audio file as request body:
Second example show same request but this time audio file is just some raw unknown data:
Note you can add multiple contents inside a
MultipartFormData. For instance here we send both a audio file and an image:Constant paths
You can declare constant paths if needed (refer to Path documentation to see more):
Interceptor
When using Session you can add automatic behavior to your requests/responses using
Interceptorlike authentication, logging, request retrying, etc…RequestInterceptorRequestInterceptorallows to adapt and/or retry a request:adaptRequestmethod is called before making a request allowing you to transform it adding headers, changing path, …rescueRequestErroris called whenever the request fail. You’ll have a chance to retry the request. This can be used to re-authenticate the user for instanceResponseInterceptorResponseInterceptoris dedicated to intercept and server responses:adaptResponsechange the server outputreceivedResponsenotify about the server final response (a valid output or error)