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 BodyProvider
s 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 BodyProvider
s you should
capture the input data in the closure provided at initialization. This means that most BodyProvider
s 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-Type
field 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) -> BodyProvider
Parameters
data
The data to set as the body.
contentType
The
Content-Type
ofdata
. 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) -> BodyProvider
Parameters
stream
The stream to set as the body.
contentType
The
Content-Type
ofstream
. Defaults toapplication/octet-stream
. -
A body provider that produces a UTF-8 encoded body.
Throws
A TextBodyEncodingError if
text
is not valid UTF-8 text.Declaration
Swift
static func text(_ text: String) -> BodyProvider
Parameters
text
The 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 : Encodable
Parameters
value
The value to encode as the request’s body.
encoder
The encoder to encode
value
with. Defaults toJSONEncoder()
.