123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116 |
- import Foundation
- public protocol DataResponseSerializerProtocol {
-
- associatedtype SerializedObject
-
-
-
-
-
-
-
-
-
-
- func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject
- }
- public protocol DownloadResponseSerializerProtocol {
-
- associatedtype SerializedObject
-
-
-
-
-
-
-
-
-
-
- func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject
- }
- public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol {
-
- var dataPreprocessor: DataPreprocessor { get }
-
- var emptyRequestMethods: Set<HTTPMethod> { get }
-
- var emptyResponseCodes: Set<Int> { get }
- }
- public protocol DataPreprocessor {
-
-
- func preprocess(_ data: Data) throws -> Data
- }
- public struct PassthroughPreprocessor: DataPreprocessor {
- public init() {}
- public func preprocess(_ data: Data) throws -> Data { data }
- }
- public struct GoogleXSSIPreprocessor: DataPreprocessor {
- public init() {}
- public func preprocess(_ data: Data) throws -> Data {
- (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data
- }
- }
- extension ResponseSerializer {
-
- public static var defaultDataPreprocessor: DataPreprocessor { PassthroughPreprocessor() }
-
- public static var defaultEmptyRequestMethods: Set<HTTPMethod> { [.head] }
-
- public static var defaultEmptyResponseCodes: Set<Int> { [204, 205] }
- public var dataPreprocessor: DataPreprocessor { Self.defaultDataPreprocessor }
- public var emptyRequestMethods: Set<HTTPMethod> { Self.defaultEmptyRequestMethods }
- public var emptyResponseCodes: Set<Int> { Self.defaultEmptyResponseCodes }
-
-
-
-
-
- public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? {
- request.flatMap { $0.httpMethod }
- .flatMap(HTTPMethod.init)
- .map { emptyRequestMethods.contains($0) }
- }
-
-
-
-
-
- public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? {
- response.flatMap { $0.statusCode }
- .map { emptyResponseCodes.contains($0) }
- }
-
-
-
-
-
-
-
- public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool {
- (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true)
- }
- }
- extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol {
- public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject {
- guard error == nil else { throw error! }
- guard let fileURL = fileURL else {
- throw AFError.responseSerializationFailed(reason: .inputFileNil)
- }
- let data: Data
- do {
- data = try Data(contentsOf: fileURL)
- } catch {
- throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))
- }
- do {
- return try serialize(request: request, response: response, data: data, error: error)
- } catch {
- throw error
- }
- }
- }
- extension DataRequest {
-
-
-
-
-
-
-
- @discardableResult
- public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse<Data?>) -> Void) -> Self {
- appendResponseSerializer {
-
- let result = AFResult<Data?>(value: self.data, error: self.error)
-
- self.underlyingQueue.async {
- let response = DataResponse(request: self.request,
- response: self.response,
- data: self.data,
- metrics: self.metrics,
- serializationDuration: 0,
- result: result)
- self.eventMonitor?.request(self, didParseResponse: response)
- self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
- }
- }
- return self
- }
-
-
-
-
-
-
-
-
- @discardableResult
- public func response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
- responseSerializer: Serializer,
- completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
- -> Self {
- appendResponseSerializer {
-
- let start = ProcessInfo.processInfo.systemUptime
- let result: AFResult<Serializer.SerializedObject> = Result {
- try responseSerializer.serialize(request: self.request,
- response: self.response,
- data: self.data,
- error: self.error)
- }.mapError { error in
- error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
- }
- let end = ProcessInfo.processInfo.systemUptime
-
- self.underlyingQueue.async {
- let response = DataResponse(request: self.request,
- response: self.response,
- data: self.data,
- metrics: self.metrics,
- serializationDuration: end - start,
- result: result)
- self.eventMonitor?.request(self, didParseResponse: response)
- guard let serializerError = result.failure, let delegate = self.delegate else {
- self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
- return
- }
- delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
- var didComplete: (() -> Void)?
- defer {
- if let didComplete = didComplete {
- self.responseSerializerDidComplete { queue.async { didComplete() } }
- }
- }
- switch retryResult {
- case .doNotRetry:
- didComplete = { completionHandler(response) }
- case let .doNotRetryWithError(retryError):
- let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
- let response = DataResponse(request: self.request,
- response: self.response,
- data: self.data,
- metrics: self.metrics,
- serializationDuration: end - start,
- result: result)
- didComplete = { completionHandler(response) }
- case .retry, .retryWithDelay:
- delegate.retryRequest(self, withDelay: retryResult.delay)
- }
- }
- }
- }
- return self
- }
- }
- extension DownloadRequest {
-
-
-
-
-
-
-
- @discardableResult
- public func response(queue: DispatchQueue = .main,
- completionHandler: @escaping (AFDownloadResponse<URL?>) -> Void)
- -> Self {
- appendResponseSerializer {
-
- let result = AFResult<URL?>(value: self.fileURL, error: self.error)
-
- self.underlyingQueue.async {
- let response = DownloadResponse(request: self.request,
- response: self.response,
- fileURL: self.fileURL,
- resumeData: self.resumeData,
- metrics: self.metrics,
- serializationDuration: 0,
- result: result)
- self.eventMonitor?.request(self, didParseResponse: response)
- self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
- }
- }
- return self
- }
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func response<Serializer: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
- responseSerializer: Serializer,
- completionHandler: @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
- -> Self {
- appendResponseSerializer {
-
- let start = ProcessInfo.processInfo.systemUptime
- let result: AFResult<Serializer.SerializedObject> = Result {
- try responseSerializer.serializeDownload(request: self.request,
- response: self.response,
- fileURL: self.fileURL,
- error: self.error)
- }.mapError { error in
- error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
- }
- let end = ProcessInfo.processInfo.systemUptime
-
- self.underlyingQueue.async {
- let response = DownloadResponse(request: self.request,
- response: self.response,
- fileURL: self.fileURL,
- resumeData: self.resumeData,
- metrics: self.metrics,
- serializationDuration: end - start,
- result: result)
- self.eventMonitor?.request(self, didParseResponse: response)
- guard let serializerError = result.failure, let delegate = self.delegate else {
- self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
- return
- }
- delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
- var didComplete: (() -> Void)?
- defer {
- if let didComplete = didComplete {
- self.responseSerializerDidComplete { queue.async { didComplete() } }
- }
- }
- switch retryResult {
- case .doNotRetry:
- didComplete = { completionHandler(response) }
- case let .doNotRetryWithError(retryError):
- let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
- let response = DownloadResponse(request: self.request,
- response: self.response,
- fileURL: self.fileURL,
- resumeData: self.resumeData,
- metrics: self.metrics,
- serializationDuration: end - start,
- result: result)
- didComplete = { completionHandler(response) }
- case .retry, .retryWithDelay:
- delegate.retryRequest(self, withDelay: retryResult.delay)
- }
- }
- }
- }
- return self
- }
- }
- public struct URLResponseSerializer: DownloadResponseSerializerProtocol {
-
- public init() {}
- public func serializeDownload(request: URLRequest?,
- response: HTTPURLResponse?,
- fileURL: URL?,
- error: Error?) throws -> URL {
- guard error == nil else { throw error! }
- guard let url = fileURL else {
- throw AFError.responseSerializationFailed(reason: .inputFileNil)
- }
- return url
- }
- }
- extension DownloadRequest {
-
-
-
-
-
-
-
- @discardableResult
- public func responseURL(queue: DispatchQueue = .main,
- completionHandler: @escaping (AFDownloadResponse<URL>) -> Void) -> Self {
- response(queue: queue, responseSerializer: URLResponseSerializer(), completionHandler: completionHandler)
- }
- }
- public final class DataResponseSerializer: ResponseSerializer {
- public let dataPreprocessor: DataPreprocessor
- public let emptyResponseCodes: Set<Int>
- public let emptyRequestMethods: Set<HTTPMethod>
-
-
-
-
-
-
- public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
- emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) {
- self.dataPreprocessor = dataPreprocessor
- self.emptyResponseCodes = emptyResponseCodes
- self.emptyRequestMethods = emptyRequestMethods
- }
- public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data {
- guard error == nil else { throw error! }
- guard var data = data, !data.isEmpty else {
- guard emptyResponseAllowed(forRequest: request, response: response) else {
- throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
- }
- return Data()
- }
- data = try dataPreprocessor.preprocess(data)
- return data
- }
- }
- extension DataRequest {
-
-
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func responseData(queue: DispatchQueue = .main,
- dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
- emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
- completionHandler: @escaping (AFDataResponse<Data>) -> Void) -> Self {
- response(queue: queue,
- responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
- emptyResponseCodes: emptyResponseCodes,
- emptyRequestMethods: emptyRequestMethods),
- completionHandler: completionHandler)
- }
- }
- extension DownloadRequest {
-
-
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func responseData(queue: DispatchQueue = .main,
- dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
- emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
- completionHandler: @escaping (AFDownloadResponse<Data>) -> Void) -> Self {
- response(queue: queue,
- responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
- emptyResponseCodes: emptyResponseCodes,
- emptyRequestMethods: emptyRequestMethods),
- completionHandler: completionHandler)
- }
- }
- public final class StringResponseSerializer: ResponseSerializer {
- public let dataPreprocessor: DataPreprocessor
-
- public let encoding: String.Encoding?
- public let emptyResponseCodes: Set<Int>
- public let emptyRequestMethods: Set<HTTPMethod>
-
-
-
-
-
-
-
-
- public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
- encoding: String.Encoding? = nil,
- emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) {
- self.dataPreprocessor = dataPreprocessor
- self.encoding = encoding
- self.emptyResponseCodes = emptyResponseCodes
- self.emptyRequestMethods = emptyRequestMethods
- }
- public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String {
- guard error == nil else { throw error! }
- guard var data = data, !data.isEmpty else {
- guard emptyResponseAllowed(forRequest: request, response: response) else {
- throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
- }
- return ""
- }
- data = try dataPreprocessor.preprocess(data)
- var convertedEncoding = encoding
- if let encodingName = response?.textEncodingName, convertedEncoding == nil {
- convertedEncoding = String.Encoding(ianaCharsetName: encodingName)
- }
- let actualEncoding = convertedEncoding ?? .isoLatin1
- guard let string = String(data: data, encoding: actualEncoding) else {
- throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))
- }
- return string
- }
- }
- extension DataRequest {
-
-
-
-
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func responseString(queue: DispatchQueue = .main,
- dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
- encoding: String.Encoding? = nil,
- emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
- completionHandler: @escaping (AFDataResponse<String>) -> Void) -> Self {
- response(queue: queue,
- responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
- encoding: encoding,
- emptyResponseCodes: emptyResponseCodes,
- emptyRequestMethods: emptyRequestMethods),
- completionHandler: completionHandler)
- }
- }
- extension DownloadRequest {
-
-
-
-
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func responseString(queue: DispatchQueue = .main,
- dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
- encoding: String.Encoding? = nil,
- emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
- completionHandler: @escaping (AFDownloadResponse<String>) -> Void) -> Self {
- response(queue: queue,
- responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
- encoding: encoding,
- emptyResponseCodes: emptyResponseCodes,
- emptyRequestMethods: emptyRequestMethods),
- completionHandler: completionHandler)
- }
- }
- public final class JSONResponseSerializer: ResponseSerializer {
- public let dataPreprocessor: DataPreprocessor
- public let emptyResponseCodes: Set<Int>
- public let emptyRequestMethods: Set<HTTPMethod>
-
- public let options: JSONSerialization.ReadingOptions
-
-
-
-
-
-
-
- public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
- emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
- options: JSONSerialization.ReadingOptions = .allowFragments) {
- self.dataPreprocessor = dataPreprocessor
- self.emptyResponseCodes = emptyResponseCodes
- self.emptyRequestMethods = emptyRequestMethods
- self.options = options
- }
- public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any {
- guard error == nil else { throw error! }
- guard var data = data, !data.isEmpty else {
- guard emptyResponseAllowed(forRequest: request, response: response) else {
- throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
- }
- return NSNull()
- }
- data = try dataPreprocessor.preprocess(data)
- do {
- return try JSONSerialization.jsonObject(with: data, options: options)
- } catch {
- throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))
- }
- }
- }
- extension DataRequest {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func responseJSON(queue: DispatchQueue = .main,
- dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
- emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
- options: JSONSerialization.ReadingOptions = .allowFragments,
- completionHandler: @escaping (AFDataResponse<Any>) -> Void) -> Self {
- response(queue: queue,
- responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
- emptyResponseCodes: emptyResponseCodes,
- emptyRequestMethods: emptyRequestMethods,
- options: options),
- completionHandler: completionHandler)
- }
- }
- extension DownloadRequest {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func responseJSON(queue: DispatchQueue = .main,
- dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
- emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
- options: JSONSerialization.ReadingOptions = .allowFragments,
- completionHandler: @escaping (AFDownloadResponse<Any>) -> Void) -> Self {
- response(queue: queue,
- responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
- emptyResponseCodes: emptyResponseCodes,
- emptyRequestMethods: emptyRequestMethods,
- options: options),
- completionHandler: completionHandler)
- }
- }
- public protocol EmptyResponse {
-
-
-
- static func emptyValue() -> Self
- }
- public struct Empty: Codable {
-
- public static let value = Empty()
- }
- extension Empty: EmptyResponse {
- public static func emptyValue() -> Empty {
- value
- }
- }
- public protocol DataDecoder {
-
-
-
-
-
-
-
-
- func decode<D: Decodable>(_ type: D.Type, from data: Data) throws -> D
- }
- extension JSONDecoder: DataDecoder {}
- extension PropertyListDecoder: DataDecoder {}
- public final class DecodableResponseSerializer<T: Decodable>: ResponseSerializer {
- public let dataPreprocessor: DataPreprocessor
-
- public let decoder: DataDecoder
- public let emptyResponseCodes: Set<Int>
- public let emptyRequestMethods: Set<HTTPMethod>
-
-
-
-
-
-
-
- public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor,
- decoder: DataDecoder = JSONDecoder(),
- emptyResponseCodes: Set<Int> = DecodableResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer.defaultEmptyRequestMethods) {
- self.dataPreprocessor = dataPreprocessor
- self.decoder = decoder
- self.emptyResponseCodes = emptyResponseCodes
- self.emptyRequestMethods = emptyRequestMethods
- }
- public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
- guard error == nil else { throw error! }
- guard var data = data, !data.isEmpty else {
- guard emptyResponseAllowed(forRequest: request, response: response) else {
- throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
- }
- guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else {
- throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)"))
- }
- return emptyValue
- }
- data = try dataPreprocessor.preprocess(data)
- do {
- return try decoder.decode(T.self, from: data)
- } catch {
- throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
- }
- }
- }
- extension DataRequest {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
- queue: DispatchQueue = .main,
- dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
- decoder: DataDecoder = JSONDecoder(),
- emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
- completionHandler: @escaping (AFDataResponse<T>) -> Void) -> Self {
- response(queue: queue,
- responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
- decoder: decoder,
- emptyResponseCodes: emptyResponseCodes,
- emptyRequestMethods: emptyRequestMethods),
- completionHandler: completionHandler)
- }
- }
- extension DownloadRequest {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
- queue: DispatchQueue = .main,
- dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
- decoder: DataDecoder = JSONDecoder(),
- emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
- completionHandler: @escaping (AFDownloadResponse<T>) -> Void) -> Self {
- response(queue: queue,
- responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
- decoder: decoder,
- emptyResponseCodes: emptyResponseCodes,
- emptyRequestMethods: emptyRequestMethods),
- completionHandler: completionHandler)
- }
- }
- public protocol DataStreamSerializer {
-
- associatedtype SerializedObject
-
-
-
-
-
- func serialize(_ data: Data) throws -> SerializedObject
- }
- public struct DecodableStreamSerializer<T: Decodable>: DataStreamSerializer {
-
- public let decoder: DataDecoder
-
- public let dataPreprocessor: DataPreprocessor
-
-
-
-
- public init(decoder: DataDecoder = JSONDecoder(), dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) {
- self.decoder = decoder
- self.dataPreprocessor = dataPreprocessor
- }
- public func serialize(_ data: Data) throws -> T {
- let processedData = try dataPreprocessor.preprocess(data)
- do {
- return try decoder.decode(T.self, from: processedData)
- } catch {
- throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
- }
- }
- }
- public struct PassthroughStreamSerializer: DataStreamSerializer {
- public func serialize(_ data: Data) throws -> Data { data }
- }
- public struct StringStreamSerializer: DataStreamSerializer {
- public func serialize(_ data: Data) throws -> String {
- String(decoding: data, as: UTF8.self)
- }
- }
- extension DataStreamRequest {
-
-
-
-
-
-
-
- @discardableResult
- public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler<Data, Never>) -> Self {
- let parser = { [unowned self] (data: Data) in
- queue.async {
- self.capturingError {
- try stream(.init(event: .stream(.success(data)), token: .init(self)))
- }
- self.updateAndCompleteIfPossible()
- }
- }
- $streamMutableState.write { $0.streams.append(parser) }
- appendStreamCompletion(on: queue, stream: stream)
- return self
- }
-
-
-
-
-
-
-
-
- @discardableResult
- public func responseStream<Serializer: DataStreamSerializer>(using serializer: Serializer,
- on queue: DispatchQueue = .main,
- stream: @escaping Handler<Serializer.SerializedObject, AFError>) -> Self {
- let parser = { [unowned self] (data: Data) in
- self.serializationQueue.async {
-
- let result = Result { try serializer.serialize(data) }
- .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) }
-
- self.underlyingQueue.async {
- self.eventMonitor?.request(self, didParseStream: result)
- if result.isFailure, self.automaticallyCancelOnStreamError {
- self.cancel()
- }
- queue.async {
- self.capturingError {
- try stream(.init(event: .stream(result), token: .init(self)))
- }
- self.updateAndCompleteIfPossible()
- }
- }
- }
- }
- $streamMutableState.write { $0.streams.append(parser) }
- appendStreamCompletion(on: queue, stream: stream)
- return self
- }
-
-
-
-
-
-
-
- @discardableResult
- public func responseStreamString(on queue: DispatchQueue = .main,
- stream: @escaping Handler<String, Never>) -> Self {
- let parser = { [unowned self] (data: Data) in
- self.serializationQueue.async {
-
- let string = String(decoding: data, as: UTF8.self)
-
- self.underlyingQueue.async {
- self.eventMonitor?.request(self, didParseStream: .success(string))
- queue.async {
- self.capturingError {
- try stream(.init(event: .stream(.success(string)), token: .init(self)))
- }
- self.updateAndCompleteIfPossible()
- }
- }
- }
- }
- $streamMutableState.write { $0.streams.append(parser) }
- appendStreamCompletion(on: queue, stream: stream)
- return self
- }
- private func updateAndCompleteIfPossible() {
- $streamMutableState.write { state in
- state.numberOfExecutingStreams -= 1
- guard state.numberOfExecutingStreams == 0, !state.enqueuedCompletionEvents.isEmpty else { return }
- let completionEvents = state.enqueuedCompletionEvents
- self.underlyingQueue.async { completionEvents.forEach { $0() } }
- state.enqueuedCompletionEvents.removeAll()
- }
- }
-
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func responseStreamDecodable<T: Decodable>(of type: T.Type = T.self,
- on queue: DispatchQueue = .main,
- using decoder: DataDecoder = JSONDecoder(),
- preprocessor: DataPreprocessor = PassthroughPreprocessor(),
- stream: @escaping Handler<T, AFError>) -> Self {
- responseStream(using: DecodableStreamSerializer<T>(decoder: decoder, dataPreprocessor: preprocessor),
- stream: stream)
- }
- }
|