Alamofire源码解析 - ResponseSerialization

首先定义了两个协议DataResponseSerializerProtocolDownloadResponseSerializerProtocol,以及这两个协议的实现类型,这两个协议都有一个serializeResponse属性,返回Result的闭包。

extension DataRequest

其中两个方法添加完成操作到delegate.queue

    public func response(queue: DispatchQueue? = nil, completionHandler:
 @escaping (DefaultDataResponse) -> Void) -> Self 

    public func response(
        queue: DispatchQueue? = nil,
        responseSerializer: T,
        completionHandler: @escaping
 (DataResponse) -> Void)
        -> Self

DownloadRequest

也有两个方法,都是一样的结构

    public func response(
        queue: DispatchQueue? = nil,
        completionHandler: @escaping (DefaultDownloadResponse) -> Void)
        -> Self

    public func response(
        queue: DispatchQueue? = nil,
        responseSerializer: T,
        completionHandler: @escaping (DownloadResponse) -> Void)
        -> Self

下面的代码有四部分对应返回数据解析的四种类型

  • Data
  • String
  • JSON
  • Property List

这四部分代码都是相同的结构,这里以Data为例。

Data

Request的扩展类方法返回Result

    public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result {
        guard error == nil else { return .failure(error!) }

        if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) }

        guard let validData = data else {
            return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
        }

        return .success(validData)
    }

extension DataRequest {
    /// Creates a response serializer that returns the associated data as-is.
    ///
    /// - returns: A data response serializer.
    public static func dataResponseSerializer() -> DataResponseSerializer {
        return DataResponseSerializer { _, response, data, error in
            return Request.serializeResponseData(response: response, data: data, error: error)
        }
    }

    /// Adds a handler to be called once the request has finished.
    ///
    /// - parameter completionHandler: The code to be executed once the request has finished.
    ///
    /// - returns: The request.
    @discardableResult
    public func responseData(
        queue: DispatchQueue? = nil,
        completionHandler: @escaping (DataResponse) -> Void)
        -> Self
    {
        return response(
            queue: queue,
            responseSerializer: DataRequest.dataResponseSerializer(),
            completionHandler: completionHandler
        )
    }
}

调用上面定义的response方法

你可能感兴趣的:(Alamofire源码解析 - ResponseSerialization)