首先定义了两个协议DataResponseSerializerProtocol
和DownloadResponseSerializerProtocol
,以及这两个协议的实现类型,这两个协议都有一个serializeResponse
属性,返回Result<Value>
的闭包。
extension DataRequest
其中两个方法添加完成操作到delegate.queue
public func response(queue: DispatchQueue? = nil, completionHandler:
@escaping (DefaultDataResponse) -> Void) -> Self
public func response<T: DataResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping
(DataResponse<T.SerializedObject>) -> Void)
-> Self
DownloadRequest
也有两个方法,都是一样的结构
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DefaultDownloadResponse) -> Void)
-> Self
public func response<T: DownloadResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void)
-> Self
下面的代码有四部分对应返回数据解析的四种类型
- Data
- String
- JSON
- Property List
这四部分代码都是相同的结构,这里以Data
为例。
Data
Request的扩展类方法返回Result<Data>
public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Data> {
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<Data> {
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<Data>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.dataResponseSerializer(),
completionHandler: completionHandler
)
}
}
调用上面定义的response
方法