BodyProvider
public struct BodyProvider
A type that produces the body of a request and updates the header of a request accordingly.
A BodyProvider implements a function that takes an inout Header and produces a RequestBody. In the
body(updating:) method, the provider should construct the RequestBody and update the Content-Type of the
provided Header. The provider can also set any other relevant fields in the header.
Several predefined BodyProviders are provided for text bodies and JSON bodies.
Creating a BodyProvider
The body(updating:) method is defined when the BodyProvider is initialised as a closure. The method is somewhat
odd because it doesn’t take any data to convert to a RequestBody as input. In your BodyProviders you should
capture the input data in the closure provided at initialization. This means that most BodyProviders will be
provided by factory functions that take the input data and construct a new body provider using it.
When implementing a provider, ensure that updates to the provided header are only applied when any throwing
functions have succeeded. Otherwise you may end up in the situation where the header of a request is updated but its
body has not been created because an error was thrown during creation.
-
Undocumented
Declaration
Swift
public init(encode: @escaping (inout Header) throws -> RequestBody) -
Undocumented
Declaration
Swift
public func body(updating header: inout Header) throws -> RequestBody
-
An empty
BodyProvider. This provider never throws an error, removes theContent-Typefield of the header and always produces aRequestBody.none.Declaration
Swift
static let none: BodyProvider -
A body provider that wraps some raw data.
This provider never throws an error.
Declaration
Swift
static func raw(data: Data, contentType: MediaType = .binary) -> BodyProviderParameters
dataThe data to set as the body.
contentTypeThe
Content-Typeofdata. Defaults toapplication/octet-stream. -
A body provider that wraps a raw input stream.
This provider never throws an error.
Declaration
Swift
static func raw(stream: InputStream, contentType: MediaType = .binary) -> BodyProviderParameters
streamThe stream to set as the body.
contentTypeThe
Content-Typeofstream. Defaults toapplication/octet-stream. -
A body provider that produces a UTF-8 encoded body.
Throws
A TextBodyEncodingError if
textis not valid UTF-8 text.Declaration
Swift
static func text(_ text: String) -> BodyProviderParameters
textThe text to set as the body of the request.
-
A body provider that produces a JSON body representation of a value.
Throws
Any error that can be thrown by
JSONEncoder.Declaration
Swift
static func json<T>(encoded value: T, using encoder: JSONEncoder = JSONEncoder()) -> BodyProvider where T : EncodableParameters
valueThe value to encode as the request’s body.
encoderThe encoder to encode
valuewith. Defaults toJSONEncoder().
View on GitHub
BodyProvider Structure Reference