1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270 |
- 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 DataPreprocessor where Self == PassthroughPreprocessor {
-
- public static var passthrough: PassthroughPreprocessor { PassthroughPreprocessor() }
- }
- extension DataPreprocessor where Self == GoogleXSSIPreprocessor {
-
- public static var googleXSSI: GoogleXSSIPreprocessor { GoogleXSSIPreprocessor() }
- }
- 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(\.httpMethod)
- .flatMap(HTTPMethod.init)
- .map { emptyRequestMethods.contains($0) }
- }
-
-
-
-
-
- public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? {
- response.map(\.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
- }
- private 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 !self.isCancelled, 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
- }
-
-
-
-
-
-
-
-
- @discardableResult
- public func response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
- responseSerializer: Serializer,
- completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
- -> Self {
- _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
- }
-
-
-
-
-
-
-
-
- @discardableResult
- public func response<Serializer: ResponseSerializer>(queue: DispatchQueue = .main,
- responseSerializer: Serializer,
- completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
- -> Self {
- _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
- }
- }
- 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
- }
- private 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
- }
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func response<Serializer: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
- responseSerializer: Serializer,
- completionHandler: @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
- -> Self {
- _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
- }
-
-
-
-
-
-
-
-
-
- @discardableResult
- public func response<Serializer: ResponseSerializer>(queue: DispatchQueue = .main,
- responseSerializer: Serializer,
- completionHandler: @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
- -> Self {
- _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
- }
- }
- 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 DownloadResponseSerializerProtocol where Self == URLResponseSerializer {
-
- public static var url: URLResponseSerializer { URLResponseSerializer() }
- }
- 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 ResponseSerializer where Self == DataResponseSerializer {
-
- public static var data: DataResponseSerializer { DataResponseSerializer() }
-
-
-
-
-
-
-
-
- public static func data(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
- emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponseSerializer {
- DataResponseSerializer(dataPreprocessor: dataPreprocessor,
- emptyResponseCodes: emptyResponseCodes,
- emptyRequestMethods: emptyRequestMethods)
- }
- }
- 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 ResponseSerializer where Self == StringResponseSerializer {
-
- public static var string: StringResponseSerializer { StringResponseSerializer() }
-
-
-
-
-
-
-
-
-
-
- public static func string(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
- encoding: String.Encoding? = nil,
- emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> StringResponseSerializer {
- StringResponseSerializer(dataPreprocessor: dataPreprocessor,
- encoding: encoding,
- emptyResponseCodes: emptyResponseCodes,
- emptyRequestMethods: emptyRequestMethods)
- }
- }
- 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)
- }
- }
- @available(*, deprecated, message: "JSONResponseSerializer deprecated and will be removed in Alamofire 6. Use DecodableResponseSerializer instead.")
- 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 {
-
-
-
-
-
-
-
-
-
-
-
-
-
- @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.")
- @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 {
-
-
-
-
-
-
-
-
-
-
-
-
-
- @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.")
- @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 ResponseSerializer {
-
-
-
-
-
-
-
-
-
-
- public static func decodable<T: Decodable>(of type: T.Type,
- dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
- decoder: DataDecoder = JSONDecoder(),
- emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
- emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods) -> DecodableResponseSerializer<T> where Self == DecodableResponseSerializer<T> {
- DecodableResponseSerializer<T>(dataPreprocessor: dataPreprocessor,
- decoder: decoder,
- emptyResponseCodes: emptyResponseCodes,
- emptyRequestMethods: emptyRequestMethods)
- }
- }
- 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 init() {}
- public func serialize(_ data: Data) throws -> Data { data }
- }
- public struct StringStreamSerializer: DataStreamSerializer {
-
- public init() {}
- public func serialize(_ data: Data) throws -> String {
- String(decoding: data, as: UTF8.self)
- }
- }
- extension DataStreamSerializer {
-
-
-
-
-
-
-
- public static func decodable<T: Decodable>(of type: T.Type,
- decoder: DataDecoder = JSONDecoder(),
- dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) -> Self where Self == DecodableStreamSerializer<T> {
- DecodableStreamSerializer<T>(decoder: decoder, dataPreprocessor: dataPreprocessor)
- }
- }
- extension DataStreamSerializer where Self == PassthroughStreamSerializer {
-
- public static var passthrough: PassthroughStreamSerializer { PassthroughStreamSerializer() }
- }
- extension DataStreamSerializer where Self == StringStreamSerializer {
-
- public static var string: StringStreamSerializer { StringStreamSerializer() }
- }
- 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
- 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
- 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)
- }
- }
|