Back to Alamofire

DataStreamRequest

docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DataStreamRequest.html

5.12.017.8 KB
Original Source

DataStreamRequest

public final class DataStreamRequest : Request, @unchecked Sendable

Request subclass which streams HTTP response Data through a Handler closure.

`

                Handler
                `

Closure type handling DataStreamRequest.Stream values.

Declaration

Swift

public typealias Handler<Success, Failure> = @Sendable (Stream<Success, Failure>) throws -> Void where Failure : Error

`

                Stream
                `

Type encapsulating an Event as it flows through the stream, as well as a CancellationToken which can be used to stop the stream at any time.

See more

Declaration

Swift

public struct Stream<Success, Failure> : Sendable where Success : Sendable, Failure : Error

`

                Event
                `

Type representing an event flowing through the stream. Contains either the Result of processing streamed Data or the completion of the stream.

See more

Declaration

Swift

public enum Event<Success, Failure> : Sendable where Success : Sendable, Failure : Error

`

                Completion
                `

Value containing the state of a DataStreamRequest when the stream was completed.

See more

Declaration

Swift

public struct Completion : Sendable

`

                CancellationToken
                `

Type used to cancel an ongoing stream.

See more

Declaration

Swift

public struct CancellationToken : Sendable

`

                convertible
                `

URLRequestConvertible value used to create URLRequests for this instance.

Declaration

Swift

public let convertible: any URLRequestConvertible

`

                automaticallyCancelOnStreamError
                `

Whether or not the instance will be cancelled if stream parsing encounters an error.

Declaration

Swift

public let automaticallyCancelOnStreamError: Bool

`

                validate(_:)
                `

Validates the URLRequest and HTTPURLResponse received for the instance using the provided Validation closure.

Declaration

Swift

@discardableResult
public func validate(_ validation: @escaping Validation) -> Self

Parameters

| validation |

Validation closure used to validate the request and response.

|

Return Value

The DataStreamRequest.

`

                asInputStream(bufferSize:)
                `

Produces an InputStream that receives the Data received by the instance.

Note

The InputStream produced by this method must have open() called before being able to read Data. Additionally, this method will automatically call resume() on the instance, regardless of whether or not the creating session has startRequestsImmediately set to true.

Declaration

Swift

public func asInputStream(bufferSize: Int = 1024) -> InputStream?

Parameters

| bufferSize |

Size, in bytes, of the buffer between the OutputStream and InputStream.

|

Return Value

The InputStream bound to the internal OutboundStream.

`

                onHTTPResponse(on:perform:)
                `

Sets a closure called whenever the DataRequest produces an HTTPURLResponse and providing a completion handler to return a ResponseDisposition value.

Declaration

Swift

@discardableResult
@_disfavoredOverload
@preconcurrency
public func onHTTPResponse(
    on queue: DispatchQueue = .main,
    perform handler: @escaping @Sendable (_ response: HTTPURLResponse,
                                          _ completionHandler: @escaping @Sendable (ResponseDisposition) -> Void) -> Void
) -> Self

Parameters

| queue |

DispatchQueue on which the closure will be called. .main by default.

| | handler |

Closure called when the instance produces an HTTPURLResponse. The completionHandler provided MUST be called, otherwise the request will never complete.

|

Return Value

The instance.

`

                onHTTPResponse(on:perform:)
                `

Sets a closure called whenever the DataRequest produces an HTTPURLResponse.

Declaration

Swift

@discardableResult
@preconcurrency
public func onHTTPResponse(on queue: DispatchQueue = .main,
                           perform handler: @escaping @Sendable (HTTPURLResponse) -> Void) -> Self

Parameters

| queue |

DispatchQueue on which the closure will be called. .main by default.

| | handler |

Closure called when the instance produces an HTTPURLResponse.

|

Return Value

The instance.

Response Serialization

`

                responseStream(on:stream:)
                `

Adds a StreamHandler which performs no parsing on incoming Data.

Declaration

Swift

@discardableResult
@preconcurrency
public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler<Data, Never>) -> Self

Parameters

| queue |

DispatchQueue on which to perform StreamHandler closure.

| | stream |

StreamHandler closure called as Data is received. May be called multiple times.

|

Return Value

The DataStreamRequest.

`

                responseStream(using:on:stream:)
                `

Adds a StreamHandler which uses the provided DataStreamSerializer to process incoming Data.

Declaration

Swift

@discardableResult
@preconcurrency
public func responseStream<Serializer: DataStreamSerializer>(using serializer: Serializer,
                                                             on queue: DispatchQueue = .main,
                                                             stream: @escaping Handler<Serializer.SerializedObject, AFError>) -> Self

Parameters

| serializer |

DataStreamSerializer used to process incoming Data. Its work is done on the serializationQueue.

| | queue |

DispatchQueue on which to perform StreamHandler closure.

| | stream |

StreamHandler closure called as Data is received. May be called multiple times.

|

Return Value

The DataStreamRequest.

`

                responseStreamString(on:stream:)
                `

Adds a StreamHandler which parses incoming Data as a UTF8 String.

Declaration

Swift

@discardableResult
@preconcurrency
public func responseStreamString(on queue: DispatchQueue = .main,
                                 stream: @escaping Handler<String, Never>) -> Self

Parameters

| queue |

DispatchQueue on which to perform StreamHandler closure.

| | stream |

StreamHandler closure called as Data is received. May be called multiple times.

|

Return Value

The DataStreamRequest.

`

                responseStreamDecodable(of:on:using:preprocessor:stream:)
                `

Adds a StreamHandler which parses incoming Data using the provided DataDecoder.

Declaration

Swift

@discardableResult
@preconcurrency
public func responseStreamDecodable<T: Decodable>(of type: T.Type = T.self,
                                                  on queue: DispatchQueue = .main,
                                                  using decoder: any DataDecoder = JSONDecoder(),
                                                  preprocessor: any DataPreprocessor = PassthroughPreprocessor(),
                                                  stream: @escaping Handler<T, AFError>) -> Self where T: Sendable

Parameters

| type |

Decodable type to parse incoming Data into.

| | queue |

DispatchQueue on which to perform StreamHandler closure.

| | decoder |

DataDecoder used to decode the incoming Data.

| | preprocessor |

DataPreprocessor used to process the incoming Data before it’s passed to the decoder.

| | stream |

StreamHandler closure called as Data is received. May be called multiple times.

|

Return Value

The DataStreamRequest.

DataRequest / UploadRequest

`

                publishStream(using:on:)
                `

Creates a DataStreamPublisher for this instance using the given DataStreamSerializer and DispatchQueue.

Declaration

Swift

@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishStream<Serializer: DataStreamSerializer>(using serializer: Serializer,
                                                            on queue: DispatchQueue = .main) -> DataStreamPublisher<Serializer.SerializedObject>

Parameters

| serializer |

DataStreamSerializer used to serialize the streamed Data.

| | queue |

DispatchQueue on which the DataRequest.Stream values will be published. .main by default.

|

Return Value

The DataStreamPublisher.

`

                publishData(queue:)
                `

Creates a DataStreamPublisher for this instance which uses a PassthroughStreamSerializer to stream Data unserialized.

Declaration

Swift

@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishData(queue: DispatchQueue = .main) -> DataStreamPublisher<Data>

Parameters

| queue |

DispatchQueue on which the DataRequest.Stream values will be published. .main by default.

|

Return Value

The DataStreamPublisher.

`

                publishString(queue:)
                `

Creates a DataStreamPublisher for this instance which uses a StringStreamSerializer to serialize stream Data values into String values.

Declaration

Swift

@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishString(queue: DispatchQueue = .main) -> DataStreamPublisher<String>

Parameters

| queue |

DispatchQueue on which the DataRequest.Stream values will be published. .main by default.

|

Return Value

The DataStreamPublisher.

`

                publishDecodable(type:queue:decoder:preprocessor:)
                `

Creates a DataStreamPublisher for this instance which uses a DecodableStreamSerializer with the provided parameters to serialize stream Data values into the provided type.

Declaration

Swift

@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishDecodable<T: Decodable>(type: T.Type = T.self,
                                           queue: DispatchQueue = .main,
                                           decoder: any DataDecoder = JSONDecoder(),
                                           preprocessor: any DataPreprocessor = PassthroughPreprocessor()) -> DataStreamPublisher<T>

Parameters

| type |

Decodable type to which to decode stream Data. Inferred from the context by default.

| | queue |

DispatchQueue on which the DataRequest.Stream values will be published. .main by default.

| | decoder |

DataDecoder instance used to decode stream Data. JSONDecoder() by default.

| | preprocessor |

DataPreprocessor which filters incoming stream Data before serialization. PassthroughPreprocessor() by default.

|

Return Value

The DataStreamPublisher.

DataStreamTask

`

                httpResponses(bufferingPolicy:)
                `

Creates a StreamOf<HTTPURLResponse> for the instance’s responses.

Declaration

Swift

public func httpResponses(bufferingPolicy: StreamOf<HTTPURLResponse>.BufferingPolicy = .unbounded) -> StreamOf<HTTPURLResponse>

Parameters

| bufferingPolicy |

BufferingPolicy that determines the stream’s buffering behavior..unbounded by default.

|

Return Value

The StreamOf<HTTPURLResponse>.

`

                onHTTPResponse(perform:)
                `

Sets an async closure returning a Request.ResponseDisposition, called whenever the DataStreamRequest produces an HTTPURLResponse.

Note

Most requests will only produce a single response for each outgoing attempt (initial + retries). However, some types of response may trigger multiple HTTPURLResponses, such as multipart streams, where responses after the first will contain the part headers.

Declaration

Swift

@discardableResult
@_disfavoredOverload
public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> ResponseDisposition) -> Self

Parameters

| handler |

Async closure executed when a new HTTPURLResponse is received and returning a ResponseDisposition value. This value determines whether to continue the request or cancel it as if cancel() had been called on the instance. Note, this closure is called on an arbitrary thread, so any synchronous calls in it will execute in that context.

|

Return Value

The instance.

`

                onHTTPResponse(perform:)
                `

Sets an async closure called whenever the DataStreamRequest produces an HTTPURLResponse.

Note

Most requests will only produce a single response for each outgoing attempt (initial + retries). However, some types of response may trigger multiple HTTPURLResponses, such as multipart streams, where responses after the first will contain the part headers.

Declaration

Swift

@discardableResult
public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> Void) -> Self

Parameters

| handler |

Async closure executed when a new HTTPURLResponse is received. Note, this closure is called on an arbitrary thread, so any synchronous calls in it will execute in that context.

|

Return Value

The instance.

`

                streamTask()
                `

Creates a DataStreamTask used to await streams of serialized values.

Declaration

Swift

public func streamTask() -> DataStreamTask

Return Value

The DataStreamTask.

`

                Validation
                `

A closure used to validate a request that takes a URLRequest and HTTPURLResponse and returns whether the request was valid.

Declaration

Swift

public typealias Validation = @Sendable (_ request: URLRequest?, _ response: HTTPURLResponse) -> ValidationResult

`

                validate(statusCode:)
                `

Validates that the response has a status code in the specified sequence.

If validation fails, subsequent calls to response handlers will have an associated error.

Declaration

Swift

@discardableResult
@preconcurrency
public func validate<S>(statusCode acceptableStatusCodes: S) -> Self where S : Sendable, S : Sequence, S.Element == Int

Parameters

| acceptableStatusCodes |

Sequence of acceptable response status codes.

|

Return Value

The instance.

`

                validate(contentType:)
                `

Validates that the response has a content type in the specified sequence.

If validation fails, subsequent calls to response handlers will have an associated error.

Declaration

Swift

@discardableResult
@preconcurrency
public func validate<S>(contentType acceptableContentTypes: @escaping @Sendable @autoclosure () -> S) -> Self where S : Sendable, S : Sequence, S.Element == String

Parameters

| contentType |

The acceptable content types, which may specify wildcard types and/or subtypes.

|

Return Value

The request.

`

                validate()
                `

Validates that the response has a status code in the default acceptable range of 200…299, and that the content type matches any specified in the Accept HTTP header field.

If validation fails, subsequent calls to response handlers will have an associated error.

Declaration

Swift

@discardableResult
public func validate() -> Self

Return Value

The instance.