NerdzNetworking is a wrapper on top of URLSession and URLRequest to simplify creating and managing network requests written on Swift language.
Example
You need to define request.
class LoginWithFacebookRequest: Request {
typealias ResponseObjectType = User
typealias ErrorType = AuthError
let path = "login/facebook"
let methong = .post
let body: RequestBody?
init(token: String) {
body = .params(
[
"token": token
]
)
}
}
And then just use it. (each call is optional and can be skipped if needed)
LoginWithFacebookRequest(token: fbToken)
.execute()
.onSuccess { user in
...
}
.onFail { error in
...
}
.onStart { operation in
...
}
.onProgress { progress in
...
}
.onDebug { info in
...
}
}
Ideology
Structure
The main ideology for creating NerdzNetworking library was to maximaly split networking into small pieces.
The ideal scenario would be to have a separate class/structure per each request. This should help easily navigate and search information for specific request in files structure.
Strong typization
Another flow that library truing to follow - predefined options for using and simplicity of using.
We are trying to use generic types on top of protocols, as well as enumerations instead of raw values. As an example - predefined headers like Content-Type or Accept. Instead of giving a possibility to put any value, we have defined and enumerations that limits possbie input only to predefined scenarios like .application(.json).
To make it simple, previously mentioned headers already have .application(.json) value preselected for you, so in case you are using standard REST API - everything ready from the box.
Tutorial
Endpoint setup
First of all you need to setup your endpoint that will be used later on for executing requests. To do that - you should be using Endpoint class.
Endpoint class will collect all general settings for performing requests. You can change any parameter at any time you want.
let endpoint = Endpoint(baseUrl: myBaseUrl)
endpoint.headers = defaultHeaders // Specifying some default headers like OS, device language, device model, etc.
endpoint.headers.authToken = .bearer(tokenString) // Specifying user token
After creating your endpoint, you can mark it as a default, so every request will pick it up automatically.
Endpoint.default = endpoint
You can change default endpoint based on configuration or environment you need.
Request creation
To create a request you should implement Request protocol. You can or have separate class per each request or an enum.
Separate class for each request
class MyRequest: Request {
typealias ResponseObjectType = MyExpectedResponse
typealias ErrorType = MyUnexpectedError
let path = "my/path/to/backend" // Required
let methong = .get // Optional
let queryParams = [("key", "value")] // Optional
let body = .params(["key", "value"]) // Optional
let headers = [RequestHeaderKey("key"): "value", .contentType: "application/json"] // Optional
let timeout = 60 // Optional, by defauld will be picked from Endpoint
let endpoint = myEndpoint // Optional, by default will be a Endpoint.default
}
This is just an example and probably you will not have all parameters required and static. To have dynamicaly created request - you can just use initializers that willl be taking dynamic parameters required for request.
As an example - some dynamic bodyParams or dynamic path.
Default request
You can use buit in class DefaultRequest to perform requests without a need to create a separate class.
NerdzNetworking library also provide an easy way of creation and execution of multipart form-data requests. You just need to implement MultipartFormDataRequest instead of Request protocol or use DefaultMultipartFormDataRequest class.
In addition to Request fields you will need to provide files field of MultipartFile protocol instances. You can implement this protocol or use DefaultMultipartFile class.
class MyMultipartRequest: MultipartFormDataRequest {
// Same fields as in Request example
let files: [MultipartFile] = [
DefaultMultipartFile(resource: fileData, mime: .image(.png), fileName: "avatar1"),
DefaultMultipartFile(resource: fileUrl, mime: .audio(.mp4), fileName: "song"),
DefaultMultipartFile(resource: filePath, mime: .image(.jpeg), fileName: "avatar2")
]
}
Request execution
To exucute request you can use next constructions:
myRequest.execute(): will execute myRequest on Endpoint.default
myRequest.execute(on: myEndpoint): will execute myRequest on myEndpoint
myEndpoint.execute(myRequest): will execute myRequest on myEndpoint
Handling execution process
To handle execution process you can use futures-style methods after execute method called. (every method is optional, so use only those you really need)
myRequest
.execute()
.responseOn(.main) // Response will be returned in `.main` queue
.retryOnFail(false) // If this request will fail - system will not try to rerun it again
.onStart { requestOperation in
// Will be called when request will start and return request operation that allow to control request during the execution
}
.onProgress { progress in
// Will provide a progress of request execution. Useful for multipart uploading requests
}
.onSuccess { response in
// Will return a response object specified in request under `ResponseType`
}
.onFail { error in
// Will return `ErrorResponse` that might contain `ErrorType` specified in request
}
.onDebug { info in
// Will return `DebugInfo` that contain a list of useful information for debugging request failure
}
Mapping
For now NerdzNetworking library supports only native Codable mapping. Tutorial.
Response converters
NerdzNetworking supports response converters that might convert response before mapping process. Might be useful if case you need to adopt response data to internal model, or to bypass parent object to map only chileds.
ResponseJsonConverter
You can also provide a response converters to convert some unpropertly returned responses beаore mapping into expected response starts. The responsible protocol for this is ResponseJsonConverter.
Response converter should be specified in Request class under responseConverter(success) or/and errorConverter(fail) fields.
You can have your own converters that implement ResponseJsonConverter protocol, or use built in implementations: KeyPathResponseConverter, ClosureResponseConverter.
KeyPathResponseConverter
KeyPathResponseConverter allow you to pull a data from JSON chileds node by specific path to the node.
class MyRequest: Request {
var responseConverter: ResponseJsonConverter {
KeyPathResponseConverter(path: "path/to/node")
}
var errorConverter: ResponseJsonConverter {
KeyPathResponseConverter(path: "path/to/error")
}
}
ClosureResponseConverter
ClosureResponseConverter allow you to provide custom convertation by closure. You will need to provide a closure that takes Any and return Any after convertation.
class MyRequest: Request {
var responseConverter: ResponseJsonConverter {
ClosureResponseConverter { response in
// Return converted response for success response
}
}
var errorConverter: ResponseJsonConverter {
ClosureResponseConverter { response in
// Return converted response for error response
}
}
}
Custom ResponseJsonConverter
You can implement your ovn converter by implementing ResponseJsonConverter protocol.
class MyResponseConverter: ResponseJsonConverter {
func convertedJson(from json: Any) throws -> Any {
// Provide convertation and return converted code
}
}
Installation
CocoaPods
You can use CocoaPods dependency manager to install NerdzNetworking.
In your Podfile spicify:
Registering closure that will be triggered when request starts processing
You can call this method several times, and every registered closure will be triggered
Name
Type
Default value
Description
closure
() -> Void
Triggered closure
func calncel()
Cancel request processing
@ Request protocol
TYPE: protocol
Protocol that represents a single request. You can imlement this protocol and then execute it. You can use DefaultRequest struct, that already implements this protocol, for executing requests.
associatedtype
Name
Type
Accessibility
Description
ResponseObjectType
ResponseObject
A type of expected response from server. It should implement ResponseObject protocol
ErrorType
ServerError
A type of expected error from server. It should implement ServerError protocol
Properties
Name
Type
Accessibility
Description
path
String
getrequired
A request path
method
HTTPMethod
getrequired
A request method
queryParams
[(String, String)]
getoptional
A request query parameters represented as an array of touples to save order
body
RequestBody?
getoptional
A request body
headers
[RequestHeaderKey: String]
getoptional
A request specific headers. Will be used is addition to headers from Endpoint
timeout
TimeInterval
getoptional
A request timeout. If not specified - will be used default from Endpoint
responseConverter
ResponseJsonConverter?
getoptional
A successful response converter. Will be converted before mapping into a ResponseObjectType
errorConverter
ResponseJsonConverter?
getoptional
An error response converter. Will be converted before mapping into a ErrorType
endpoint
Endpoint?
getoptional
An endpoint that will be used for execution
decoder
JSONDecoder?
getoptional
A JSON response decoder that will be used for decoding response. In case not provided - decoder from Endpoint will be used
Initialize DefaultRequest object with all possible parameters
Name
Type
Default value
Description
path
String
-
A request path
method
HTTPMethod
-
A request method
queryParams
[(String, String)]
[]
A request query parameters represented as an array of touples to save order
bodyParams
[String: Any]
[:]
A request body params
headers
[RequestHeaderKey: String]
[:]
A request specific headers. Will be used is addition to headers from Endpoint
timeout
TimeInterval
nil
A request timeout. If not specified - will be used default from Endpoint
responseConverter
ResponseJsonConverter?
nil
A successful response converter. Will be converted before mapping into a ResponseObjectType
errorConverter
ResponseJsonConverter?
nil
An error response converter. Will be converted before mapping into a ErrorType
endpoint
Endpoint?
nil
An endpoint that will be used for execution
decoder
JSONDecoder?
nil
A JSON response decoder that will be used for decoding response. In case not provided - decoder from Endpoint will be used
@ MultipartFormDataRequest protocol
TYPE: protocol
INHERITS: Request protocol
Protocol that represents a multipart form-data request. Protocol inherits Request protocol, and adding files property on top. So mostly it is the same as Request protocol. You can use DefaultMultipartFormDataRequest struct, that already implements this protocol, for executing multipart requests.
associatedtype
Name
Type
Accessibility
Description
ResponseObjectType
ResponseObject
A type of expected response from server. It should implement ResponseObject protocol
ErrorType
ServerError
A type of expected error from server. It should implement ServerError protocol
Properties
Name
Type
Accessibility
Description
path
String
getrequired
A request path
method
HTTPMethod
getrequired
A request method
queryParams
[(String, String)]
getoptional
A request query parameters represented as an array of touples to save order
body
RequestBody?
getoptional
A request body
headers
[RequestHeaderKey: String]
getoptional
A request specific headers. Will be used is addition to headers from Endpoint
timeout
TimeInterval
getoptional
A request timeout. If not specified - will be used default from Endpoint
responseConverter
ResponseJsonConverter?
getoptional
A successful response converter. Will be converted before mapping into a ResponseObjectType
errorConverter
ResponseJsonConverter?
getoptional
An error response converter. Will be converted before mapping into a ErrorType
endpoint
Endpoint?
getoptional
An endpoint that will be used for execution
decoder
JSONDecoder?
getoptional
A JSON response decoder that will be used for decoding response. In case not provided - decoder from Endpoint will be used
files
[MultipartFile]
getrequired
A list of files that needs to be processed with request
NerdzNetworking
NerdzNetworkingis a wrapper on top ofURLSessionandURLRequestto simplify creating and managing network requests written onSwiftlanguage.Example
You need to define request.
And then just use it. (each call is optional and can be skipped if needed)
Ideology
Structure
The main ideology for creating
NerdzNetworkinglibrary was to maximaly split networking into small pieces. The ideal scenario would be to have a separate class/structure per each request. This should help easily navigate and search information for specific request in files structure.Strong typization
Another flow that library truing to follow - predefined options for using and simplicity of using. We are trying to use generic types on top of protocols, as well as enumerations instead of raw values. As an example - predefined headers like
Content-TypeorAccept. Instead of giving a possibility to put any value, we have defined and enumerations that limits possbie input only to predefined scenarios like.application(.json). To make it simple, previously mentioned headers already have.application(.json)value preselected for you, so in case you are using standard REST API - everything ready from the box.Tutorial
Endpoint setup
First of all you need to setup your endpoint that will be used later on for executing requests. To do that - you should be using
Endpointclass.Endpointclass will collect all general settings for performing requests. You can change any parameter at any time you want.After creating your endpoint, you can mark it as a
default, so every request will pick it up automatically.You can change
defaultendpoint based on configuration or environment you need.Request creation
To create a request you should implement
Requestprotocol. You can or have separate class per each request or anenum.Separate class for each request
This is just an example and probably you will not have all parameters required and static. To have dynamicaly created request - you can just use initializers that willl be taking dynamic parameters required for request. As an example - some dynamic bodyParams or dynamic path.
Default request
You can use buit in class
DefaultRequestto perform requests without a need to create a separate class.Multipart request
NerdzNetworkinglibrary also provide an easy way of creation and execution of multipart form-data requests. You just need to implementMultipartFormDataRequestinstead ofRequestprotocol or useDefaultMultipartFormDataRequestclass.In addition to
Requestfields you will need to providefilesfield ofMultipartFileprotocol instances. You can implement this protocol or useDefaultMultipartFileclass.Request execution
To exucute request you can use next constructions:
myRequest.execute(): will executemyRequestonEndpoint.defaultmyRequest.execute(on: myEndpoint): will executemyRequestonmyEndpointmyEndpoint.execute(myRequest): will executemyRequestonmyEndpointHandling execution process
To handle execution process you can use futures-style methods after
executemethod called. (every method is optional, so use only those you really need)Mapping
For now
NerdzNetworkinglibrary supports only nativeCodablemapping. Tutorial.Response converters
NerdzNetworkingsupports response converters that might convert response before mapping process. Might be useful if case you need to adopt response data to internal model, or to bypass parent object to map only chileds.ResponseJsonConverterYou can also provide a response converters to convert some unpropertly returned responses beаore mapping into expected response starts. The responsible protocol for this is
ResponseJsonConverter.Response converter should be specified in
Requestclass underresponseConverter(success) or/anderrorConverter(fail) fields.You can have your own converters that implement
ResponseJsonConverterprotocol, or use built in implementations:KeyPathResponseConverter,ClosureResponseConverter.KeyPathResponseConverterKeyPathResponseConverterallow you to pull a data fromJSONchileds node by specificpathto the node.ClosureResponseConverterClosureResponseConverterallow you to provide custom convertation by closure. You will need to provide aclosurethat takesAnyand returnAnyafter convertation.Custom
ResponseJsonConverterYou can implement your ovn converter by implementing
ResponseJsonConverterprotocol.Installation
CocoaPods
You can use CocoaPods dependency manager to install
NerdzNetworking. In yourPodfilespicify:Swift Package Manager
To add NerdzNetworking to a Swift Package Manager based project, add:
Docummentation
@
EndpointclassClass that represents and endpoint with all settings for requests execution. You need to create at least one instance to be able to execute requests.
Properties
Endpoint.defaultEndpointstaticread-writebaseUrlURLreadonlydecoderJSONDecoder?responseQueueDispatchQueue?retryingCountIntobservationObservationManagerrequestRetryingRequestRetryingManagersessionConfigurationURLSessionConfigurationreadonlyURLSessionheaders[RequestHeaderKey: String]read-writeMethods
Initializing with all parameters
baseUrlURLdecoderJSONDecoder?nilresponseQueueDispatchQueuenilsessionConfigurationURLSessionConfiguration.defaultURLSessionretryingCountInt1headers[RequestHeaderKey: String][:]Executing request on current endpoint
requestRequestReturn cURL string representation for provided request
Sets current instance as a
defaultfor future execution@
ExecutionOperation<T>classGENERICS:
T: RequestA class that represents request operation execution parameters like
queueand completions likeonSuccess.Properties
requestTreadonlyMethods
Setting up a queue on what all completions will be called. By default
mainqueue will be usedqueueDispatchQueueSetting up a decoder that will be used for decoding JSON response or error
decoderJSONDecoderSetting up retrying count for request failings. By default it is equal to
1retryingCountIntResponseSuccessCallback = (T.ResponseObjectType) -> VoidRegistering closure that will be called if request was successful
closure(T.ResponseObjectType) -> VoidFailCallback = (ErrorResponse<T.ErrorType>) -> VoidRegistering closure that will be called if request fails
closure(ErrorResponse<T.ErrorType>) -> VoidProgressCallback = (Double) -> VoidRegistering closure that will return request processing progress
closure(Double) -> VoidDebugCallback = (DebugInfo) -> VoidRegistering closure that will return request & response information for debugging
closure(DebugInfo) -> VoidStartCallback = () -> VoidRegistering closure that will be triggered when request starts processing
closure() -> VoidCancel request processing
@
RequestprotocolTYPE:
protocolProtocol that represents a single request. You can imlement this protocol and then execute it. You can use
DefaultRequeststruct, that already implements this protocol, for executing requests.associatedtypeResponseObjectTypeResponseObjectResponseObjectprotocolErrorTypeServerErrorServerErrorprotocolProperties
pathStringgetrequiredmethodHTTPMethodgetrequiredqueryParams[(String, String)]getoptionalbodyRequestBody?getoptionalheaders[RequestHeaderKey: String]getoptionalEndpointtimeoutTimeIntervalgetoptionalEndpointresponseConverterResponseJsonConverter?getoptionalResponseObjectTypeerrorConverterResponseJsonConverter?getoptionalErrorTypeendpointEndpoint?getoptionaldecoderJSONDecoder?getoptionalEndpointwill be usedMethods
Executing current request on provided endpoint
endpointEndpointExecuting current request on
Endpoint.defaultinstance@
DefaultRequeststructTYPE:
structIMPLEMENT:
RequestA default implementation of
Requestprotocol that can be used for executing requests without creation of extra classGenerics
ResponseResponseObjectErrorServerErrorProperties
pathStringread-writemethodHTTPMethodread-writequeryParams[(String, String)]read-writebodyRequestBody?read-writeheaders[RequestHeaderKey: String]read-writeEndpointtimeoutTimeIntervalread-writeEndpointresponseConverterResponseJsonConverter?read-writeResponseObjectTypeerrorConverterResponseJsonConverter?read-writeErrorTypeendpointEndpoint?read-writedecoderJSONDecoder?read-writeEndpointwill be usedMethods
Initialize
DefaultRequestobject with all possible parameterspathStringmethodHTTPMethodqueryParams[(String, String)][]bodyParams[String: Any][:]headers[RequestHeaderKey: String][:]EndpointtimeoutTimeIntervalnilEndpointresponseConverterResponseJsonConverter?nilResponseObjectTypeerrorConverterResponseJsonConverter?nilErrorTypeendpointEndpoint?nildecoderJSONDecoder?nilEndpointwill be used@
MultipartFormDataRequestprotocolTYPE:
protocolINHERITS:
RequestprotocolProtocol that represents a multipart form-data request. Protocol inherits
Requestprotocol, and adding files property on top. So mostly it is the same asRequestprotocol. You can useDefaultMultipartFormDataRequeststruct, that already implements this protocol, for executing multipart requests.associatedtypeResponseObjectTypeResponseObjectResponseObjectprotocolErrorTypeServerErrorServerErrorprotocolProperties
pathStringgetrequiredmethodHTTPMethodgetrequiredqueryParams[(String, String)]getoptionalbodyRequestBody?getoptionalheaders[RequestHeaderKey: String]getoptionalEndpointtimeoutTimeIntervalgetoptionalEndpointresponseConverterResponseJsonConverter?getoptionalResponseObjectTypeerrorConverterResponseJsonConverter?getoptionalErrorTypeendpointEndpoint?getoptionaldecoderJSONDecoder?getoptionalEndpointwill be usedfiles[MultipartFile]getrequiredMethods
Executing current request on provided endpoint
endpointEndpointExecuting current request on
Endpoint.defaultinstance@
DefaultMultipartFormDataRequeststructTYPE:
structIMPLEMENT:
MultipartFormDataRequestA default implementation of
MultipartFormDataRequestprotocol that can be used for executing multipart requests without creation of extra classGenerics
ResponseResponseObjectErrorServerErrorProperties
pathStringread-writemethodHTTPMethodread-writequeryParams[(String, String)]read-writebodyRequestBody?read-writeheaders[RequestHeaderKey: String]read-writeEndpointtimeoutTimeIntervalread-writeEndpointresponseConverterResponseJsonConverter?read-writeResponseObjectTypeerrorConverterResponseJsonConverter?read-writeErrorTypeendpointEndpoint?read-writedecoderJSONDecoder?read-writeEndpointwill be usedfiles[MultipartFile]read-writeMethods
Initialize
DefaultMultipartFormDataRequestobject with all possible parameterspathStringmethodHTTPMethodqueryParams[(String, String)][]bodyParams[String: Any][:]headers[RequestHeaderKey: String][:]EndpointtimeoutTimeIntervalnilEndpointresponseConverterResponseJsonConverter?nilResponseObjectTypeerrorConverterResponseJsonConverter?nilErrorTypeendpointEndpoint?nildecoderJSONDecoder?nilEndpointwill be usedfiles[MultipartFile][]@
DefaultMultipartFilestructA default implementation of
MultipartFileprotocol that you can use in case you do not want to create additional class for sending multipart requestProperties
fileNameStringread-writemimeMimeTyperead-writeresourceMultipartResourceConvertableread-writeString,Data,URL,InputStreamMethods
Initialize
DefaultMultipartFileobject with all possible parametersresourceMultipartResourceConvertablemimeMimeTypefileNameStringString,Data,URL,InputStream@
ServerErrorprotocolA protocol that represents an error returned from server
Properties
messageStringgetrequiredSupported types
StringOptional@
HTTPMethodenumTYPE:
enumINHERITS:
StringAn enum that represents a request http method.
.getGEThttp method.postPOSThttp method.putPUThttp method.deleteDELETEhttp method.pathPATHhttp method@
RequestBodyenumTYPE:
enumAn enum that represents different types of request body
.rawvalue: Data.stringvalue: String.paramsvalue: [String: Any]@
DebugInfostructTYPE:
structRepresents an information for debugging networking request.
Properties
sessionConfigurationURLSessionConfigurationreadonlyURLSessionconfigurationrequestURLRequestreadonlyURLRequestthat were built for executiondataResponseData?readonlyDataformaturlResponseHTTPURLResponsereadonlyerrorResponseError?readonlyrequestDurationTimeIntervalreadonlycURLString?readonlystringResponseString?readonlyStringformatjsonResponseAny?readonlyJSONformatAPI To be continued…
Next steps
CombinesupportLicense
This code is distributed under the MIT license. See the
LICENSEfile for more info.