Response 提供了網絡請求數據完成后的回調功能,包含
- 默認數據直接回調
- 提供默認json解析、propertyList解析、data解析、string解析回調
- 自定義解析后回調
默認數據回調DefaultDataResponse
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
}
DefaultDataResponse
保存了HTTPURLResponse
、data
等信息,直接回調返回結構體對象
JSON解析
public func responseJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DataResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.jsonResponseSerializer(options: options),
completionHandler: completionHandler
)
}
JSON序列化數據
do {
let json = try JSONSerialization.jsonObject(with: validData, options: options)
return .success(json)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
}
自定義解析
.response(responseSerializer: DataResponseSerializer<String>(serializeResponse: { (urlRequest, response, data, error) -> Result<String> in
print("原始數據:\(response)")
return .success("返回一個自定義解析后成功的數據")
})) { (response) in
print(response)
}
執行自定義閉包,返回result對象,最后回調DataResponse
對象
delegate.queue.addOperation {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
var dataResponse = DataResponse<T.SerializedObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result,
timeline: self.timeline
)
dataResponse.add(self.delegate.metrics)
(queue ?? DispatchQueue.main).async { completionHandler(dataResponse) }