DownloadRequest

public final class DownloadRequest : Request, @unchecked Sendable

Request subclass which downloads Data to a file on disk using URLSessionDownloadTask.

  • A set of options to be executed prior to moving a downloaded file from the temporary URL to the destination URL.

    See more

    Declaration

    Swift

    public struct Options : OptionSet, Sendable

Destination

  • A closure executed once a DownloadRequest has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the HTTPURLResponse, and returns two values: the file URL where the temporary file should be moved and the options defining how the file should be moved.

    Note

    Downloads from a local file:// URLs do not use the Destination closure, as those downloads do not return an HTTPURLResponse. Instead the file is merely moved within the temporary directory.

    Declaration

    Swift

    public typealias Destination = @Sendable (_ temporaryURL: URL,
                                              _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  • Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.

    Declaration

    Swift

    public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
                                                   in domain: FileManager.SearchPathDomainMask = .userDomainMask,
                                                   options: Options = []) -> Destination

    Parameters

    directory

    The search path directory. .documentDirectory by default.

    domain

    The search path domain mask. .userDomainMask by default.

    options

    DownloadRequest.Options used when moving the downloaded file to its destination. None by default.

    Return Value

    The Destination closure.

Downloadable

  • Type describing the source used to create the underlying URLSessionDownloadTask.

    See more

    Declaration

    Swift

    public enum Downloadable

Mutable State

  • If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download using the download(resumingWith data:) API.

    Note

    For more information about resumeData, see Apple’s documentation.

    Declaration

    Swift

    public var resumeData: Data? { get }
  • If the download is successful, the URL where the file was downloaded.

    Declaration

    Swift

    public var fileURL: URL? { get }

Initial State

  • Downloadable value used for this instance.

    Declaration

    Swift

    public let downloadable: Downloadable
  • Creates a URLSessionTask from the provided resume data.

    Declaration

    Swift

    public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask

    Parameters

    data

    Data used to resume the download.

    session

    URLSession used to create the URLSessionTask.

    Return Value

    The URLSessionTask created.

  • Cancels the instance. Once cancelled, a DownloadRequest can no longer be resumed or suspended.

    Note

    This method will NOT produce resume data. If you wish to cancel and produce resume data, use cancel(producingResumeData:) or cancel(byProducingResumeData:).

    Declaration

    Swift

    @discardableResult
    override public func cancel() -> Self

    Return Value

    The instance.

  • Cancels the instance, optionally producing resume data. Once cancelled, a DownloadRequest can no longer be resumed or suspended.

    Note

    If producingResumeData is true, the resumeData property will be populated with any resume data, if available.

    Declaration

    Swift

    @discardableResult
    public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self

    Return Value

    The instance.

  • Cancels the instance while producing resume data. Once cancelled, a DownloadRequest can no longer be resumed or suspended.

    Note

    The resume data passed to the completion handler will also be available on the instance’s resumeData property.

    Declaration

    Swift

    @discardableResult
    @preconcurrency
    public func cancel(byProducingResumeData completionHandler: @escaping @Sendable (_ data: Data?) -> Void) -> Self

    Parameters

    completionHandler

    The completion handler that is called when the download has been successfully cancelled. It is not guaranteed to be called on a particular queue, so you may want use an appropriate queue to perform your work.

    Return Value

    The instance.

  • Validates the request, using the specified closure.

    Note

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

    Declaration

    Swift

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

    Parameters

    validation

    Validation closure to validate the response.

    Return Value

    The instance.

Response Serialization

  • Adds a handler to be called once the request has finished.

    Declaration

    Swift

    @discardableResult
    @preconcurrency
    public func response(queue: DispatchQueue = .main,
                         completionHandler: @escaping @Sendable (AFDownloadResponse<URL?>) -> Void)
        -> Self

    Parameters

    queue

    The queue on which the completion handler is dispatched. .main by default.

    completionHandler

    The code to be executed once the request has finished.

    Return Value

    The request.

  • Adds a handler to be called once the request has finished.

    Note

    This handler will read the entire downloaded file into memory, use with caution.

    Declaration

    Swift

    @discardableResult
    public func response<Serializer: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
                                                                         responseSerializer: Serializer,
                                                                         completionHandler: @escaping @Sendable (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
        -> Self

    Parameters

    queue

    The queue on which the completion handler is dispatched. .main by default.

    responseSerializer

    The response serializer responsible for serializing the request, response, and data contained in the destination URL.

    completionHandler

    The code to be executed once the request has finished.

    Return Value

    The request.

  • Adds a handler to be called once the request has finished.

    Note

    This handler will read the entire downloaded file into memory, use with caution.

    Declaration

    Swift

    @discardableResult
    public func response<Serializer: ResponseSerializer>(queue: DispatchQueue = .main,
                                                         responseSerializer: Serializer,
                                                         completionHandler: @escaping @Sendable (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
        -> Self

    Parameters

    queue

    The queue on which the completion handler is dispatched. .main by default.

    responseSerializer

    The response serializer responsible for serializing the request, response, and data contained in the destination URL.

    completionHandler

    The code to be executed once the request has finished.

    Return Value

    The request.

  • Adds a handler using a URLResponseSerializer to be called once the request is finished.

    Declaration

    Swift

    @discardableResult
    @preconcurrency
    public func responseURL(queue: DispatchQueue = .main,
                            completionHandler: @escaping @Sendable (AFDownloadResponse<URL>) -> Void) -> Self

    Parameters

    queue

    The queue on which the completion handler is called. .main by default.

    completionHandler

    A closure to be executed once the request has finished.

    Return Value

    The request.

  • Adds a handler using a DataResponseSerializer to be called once the request has finished.

    Note

    This handler will read the entire downloaded file into memory, use with caution.

    Declaration

    Swift

    @discardableResult
    @preconcurrency
    public func responseData(queue: DispatchQueue = .main,
                             dataPreprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
                             emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
                             emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
                             completionHandler: @escaping @Sendable (AFDownloadResponse<Data>) -> Void) -> Self

    Parameters

    queue

    The queue on which the completion handler is called. .main by default.

    dataPreprocessor

    DataPreprocessor which processes the received Data before calling the completionHandler. PassthroughPreprocessor() by default.

    emptyResponseCodes

    HTTP status codes for which empty responses are always valid. [204, 205] by default.

    emptyRequestMethods

    HTTPMethods for which empty responses are always valid. [.head] by default.

    completionHandler

    A closure to be executed once the request has finished.

    Return Value

    The request.

  • Adds a handler using a StringResponseSerializer to be called once the request has finished.

    Note

    This handler will read the entire downloaded file into memory, use with caution.

    Declaration

    Swift

    @discardableResult
    @preconcurrency
    public func responseString(queue: DispatchQueue = .main,
                               dataPreprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
                               encoding: String.Encoding? = nil,
                               emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
                               emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
                               completionHandler: @escaping @Sendable (AFDownloadResponse<String>) -> Void) -> Self

    Parameters

    queue

    The queue on which the completion handler is dispatched. .main by default.

    dataPreprocessor

    DataPreprocessor which processes the received Data before calling the completionHandler. PassthroughPreprocessor() by default.

    encoding

    The string encoding. Defaults to nil, in which case the encoding will be determined from the server response, falling back to the default HTTP character set, ISO-8859-1.

    emptyResponseCodes

    HTTP status codes for which empty responses are always valid. [204, 205] by default.

    emptyRequestMethods

    HTTPMethods for which empty responses are always valid. [.head] by default.

    completionHandler

    A closure to be executed once the request has finished.

    Return Value

    The request.

  • Adds a handler using a JSONResponseSerializer to be called once the request has finished.

    Note

    This handler will read the entire downloaded file into memory, use with caution.

    Declaration

    Swift

    @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.")
    @discardableResult
    @preconcurrency
    public func responseJSON(queue: DispatchQueue = .main,
                             dataPreprocessor: any DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
                             emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
                             emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
                             options: JSONSerialization.ReadingOptions = .allowFragments,
                             completionHandler: @escaping @Sendable (AFDownloadResponse<Any>) -> Void) -> Self

    Parameters

    queue

    The queue on which the completion handler is dispatched. .main by default.

    dataPreprocessor

    DataPreprocessor which processes the received Data before calling the completionHandler. PassthroughPreprocessor() by default.

    emptyResponseCodes

    HTTP status codes for which empty responses are always valid. [204, 205] by default.

    emptyRequestMethods

    HTTPMethods for which empty responses are always valid. [.head] by default.

    options

    JSONSerialization.ReadingOptions used when parsing the response. .allowFragments by default.

    completionHandler

    A closure to be executed once the request has finished.

    Return Value

    The request.

  • Adds a handler using a DecodableResponseSerializer to be called once the request has finished.

    Note

    This handler will read the entire downloaded file into memory, use with caution.

    Declaration

    Swift

    @discardableResult
    @preconcurrency
    public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
                                                queue: DispatchQueue = .main,
                                                dataPreprocessor: any DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
                                                decoder: any DataDecoder = JSONDecoder(),
                                                emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
                                                emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
                                                completionHandler: @escaping @Sendable (AFDownloadResponse<T>) -> Void) -> Self where T: Sendable

    Parameters

    type

    Decodable type to decode from response data.

    queue

    The queue on which the completion handler is dispatched. .main by default.

    dataPreprocessor

    DataPreprocessor which processes the received Data before calling the completionHandler. PassthroughPreprocessor() by default.

    decoder

    DataDecoder to use to decode the response. JSONDecoder() by default.

    emptyResponseCodes

    HTTP status codes for which empty responses are always valid. [204, 205] by default.

    emptyRequestMethods

    HTTPMethods for which empty responses are always valid. [.head] by default.

    completionHandler

    A closure to be executed once the request has finished.

    Return Value

    The request.

DataRequest / UploadRequest

DownloadTask

  • A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a destination URL, and returns whether the request was valid.

    Declaration

    Swift

    public typealias Validation = (_ request: URLRequest?,
                                   _ response: HTTPURLResponse,
                                   _ fileURL: URL?)
        -> ValidationResult
  • 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
    public func validate<S>(statusCode acceptableStatusCodes: S) -> Self where S : Sequence, S.Element == Int

    Parameters

    acceptableStatusCodes

    Sequence of acceptable response status codes.

    Return Value

    The instance.

  • 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
    public func validate<S>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S : Sequence, S.Element == String

    Parameters

    contentType

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

    Return Value

    The request.

  • 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 request.