引言
当我们完成Request
的时候,肯定要处理服务器返回的响应数据,在之前的文章中,我们讲过Alamofire
中,把Request
分为了4类Request
:
DataRequest
DownloadRequest
UploadRequest
StreamRequest
所以,有4种不同的Request
类型,那么就有与之对应的不同的Response
。
StreamRequest
因为之前没有提过,在这里,我们也不先提,然后UploadRequest
,服务器的数据响应其实很简单,只需响应一个结果,因此,是不需要对它的Response
再次进行独立的封装了。
所以,我们这里讲到2种与之相对应的Response
类型,它们是:
DefaultDataResponse/DataResponse
DefaultDownloadResponse/DownloadResponse
看下代码:
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self {
delegate.queue.addOperation {
(queue ?? DispatchQueue.main).async {
var dataResponse = DefaultDataResponse(
request: self.request,
response: self.response,
data: self.delegate.data,
error: self.delegate.error,
timeline: self.timeline
)
dataResponse.add(self.delegate.metrics)
completionHandler(dataResponse)
}
}
return self
}
当我使用这个函数方法获取响应数据,这里获取到的数据是没有经过序列化处理的数据,所以,我们这样区分,如果是返回的带有Default
开头的响应者,如DefaultDataResponse
、DefaultDownloadResponse
,这些都是没有进过序列化处理的response
方法。相反的,如果使用了序列化处理过的response
方法,返回的,应该就是DataResponse
或者是DownloadResponse
。
其实,这样的设计,更好的理解一些,我们在实际项目种,也不会把所有的参数都放在一个模型中。
接下来,我们来慢慢讲讲这些响应方法。
DefaultDataResponse
属性
DefaultDataResponse
用于响应data
或者upload
请求的未经过序列化处理的的数据。看看代码:
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The data returned by the server.
public let data: Data?
/// The error encountered while executing or validating the request.
public let error: Error?
/// The timeline of the complete lifecycle of the request.
public let timeline: Timeline
var _metrics: AnyObject?
request: URLRequest?
:表示该响应来源于那个请求response: HTTPURLResponse?
:服务器返回的响应data: Data?
:响应数据error: Error?
:在请求中可能发生的错误timeline: Timeline
:请求的时间线封装_metrics: AnyObject?
:包含了请求和响应的统计信息
为了保存数据,Alamofire
把这个类设计成了struct
,对数据操作更安全。
构造函数
当然,Alamofire
还提供了一个构造函数:
/// Creates a `DefaultDataResponse` instance from the specified parameters.
///
/// - Parameters:
/// - request: The URL request sent to the server.
/// - response: The server's response to the URL request.
/// - data: The data returned by the server.
/// - error: The error encountered while executing or validating the request.
/// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default.
/// - metrics: The task metrics containing the request / response statistics. `nil` by default.
public init(
request: URLRequest?,
response: HTTPURLResponse?,
data: Data?,
error: Error?,
timeline: Timeline = Timeline(),
metrics: AnyObject? = nil)
{
self.request = request
self.response = response
self.data = data
self.error = error
self.timeline = timeline
}
DataResponse
属性
一样的,我们先来看看它有些什么属性:
/// Used to store all data associated with a serialized response of a data or upload request.
public struct DataResponse<Value> {
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The data returned by the server.
public let data: Data?
/// The result of response serialization.
public let result: Result<Value>
/// The timeline of the complete lifecycle of the request.
public let timeline: Timeline
/// Returns the associated value of the result if it is a success, `nil` otherwise.
public var value: Value? { return result.value }
/// Returns the associated error value if the result if it is a failure, `nil` otherwise.
public var error: Error? { return result.error }
var _metrics: AnyObject?
对比我们上面的DefaultDataResponse
,可以看到,DataResponse
多了一个result
属性,该属性的存在,即是存储了序列化后的数据。result
属性的类型是Result
,关于Result
的内容,我们后面会单独讲到,这里不在详述。
构造函数
同样的,Alamofire
也提供了一个构造函数:
/// Creates a `DataResponse` instance with the specified parameters derived from response serialization.
///
/// - parameter request: The URL request sent to the server.
/// - parameter response: The server's response to the URL request.
/// - parameter data: The data returned by the server.
/// - parameter result: The result of response serialization.
/// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`.
///
/// - returns: The new `DataResponse` instance.
public init(
request: URLRequest?,
response: HTTPURLResponse?,
data: Data?,
result: Result<Value>,
timeline: Timeline = Timeline())
{
self.request = request
self.response = response
self.data = data
self.result = result
self.timeline = timeline
}
扩展
不仅如此,我们往下可以看到,DataResponse
还有扩展属性:
extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
public var description: String {
return result.debugDescription
}
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
/// response, the server data, the response serialization result and the timeline.
public var debugDescription: String {
var output: [String] = []
output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil")
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
output.append("[Data]: \(data?.count ?? 0) bytes")
output.append("[Result]: \(result.debugDescription)")
output.append("[Timeline]: \(timeline.debugDescription)")
return output.joined(separator: "\n")
}
}
DataResponse
实现了CustomStringConvertible
和CustomDebugStringConvertible
协议,因此可以自定义DataResponse
的打印信息。
我们也可以给我们模型实现这两个协议,在代码调试的时候,打印出详细的信息,比打断点来查看效率更高。
DefaultDownloadResponse
属性
我们来看下它的属性定义:
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The temporary destination URL of the data returned from the server.
public let temporaryURL: URL?
/// The final destination URL of the data returned from the server if it was moved.
public let destinationURL: URL?
/// The resume data generated if the request was cancelled.
public let resumeData: Data?
/// The error encountered while executing or validating the request.
public let error: Error?
/// The timeline of the complete lifecycle of the request.
public let timeline: Timeline
var _metrics: AnyObject?
有很多属性和前面的都有重复,我们就不说了,来看看不同的。
temporaryURL: URL?
:下载成功后,数据会被保存在这个临时URL中destinationURL: URL?
:目标URL,如果设置了该属性,那么文件会复制到该URL中resumeData: Data?
:表示可恢复的数据,对于下载任务,如果因为某种原因下载中断了,或失败了,可以使用该数据恢复之前的下载
构造函数
同样,也有相应的构造方法:
/// Creates a `DefaultDownloadResponse` instance from the specified parameters.
///
/// - Parameters:
/// - request: The URL request sent to the server.
/// - response: The server's response to the URL request.
/// - temporaryURL: The temporary destination URL of the data returned from the server.
/// - destinationURL: The final destination URL of the data returned from the server if it was moved.
/// - resumeData: The resume data generated if the request was cancelled.
/// - error: The error encountered while executing or validating the request.
/// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default.
/// - metrics: The task metrics containing the request / response statistics. `nil` by default.
public init(
request: URLRequest?,
response: HTTPURLResponse?,
temporaryURL: URL?,
destinationURL: URL?,
resumeData: Data?,
error: Error?,
timeline: Timeline = Timeline(),
metrics: AnyObject? = nil)
{
self.request = request
self.response = response
self.temporaryURL = temporaryURL
self.destinationURL = destinationURL
self.resumeData = resumeData
self.error = error
self.timeline = timeline
}
DownloadResponse
其实,也没有什么可以说了,类比上面的内容,比较学习一下,都差不多的意思,这里就不在详细说了。
常规打广告系列:
简书:Alamofire(六)-- 响应封装Response
掘金:Alamofire(六)-- 响应封装Response
小专栏:Alamofire(六)-- 响应封装Response
网友评论