一、Response
1、Response
: 信息保存者,面向对象
SessionManager.default
.request(urlString)
.response { (response) in
print("原始数据: \(response)")
}
- 点击
response
extension DataRequest {
@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
}
}
- 点击
self.delegate.data
override var data: Data? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
-
mutableData.append(data)
代理回调回来往mutableData
中添加数据
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data)
} else {
mutableData.append(data)
}
let bytesReceived = Int64(data.count)
totalBytesReceived += bytesReceived
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpected
progress.completedUnitCount = totalBytesReceived
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
2、DefaultDataResponse
和DataResponse
的区别
DataResponse
再封装了一层,序列化层
二、序列化
1、自定义序列化
let dyzResponseSerilizer = DataResponseSerializer.init { (request, response, data, error) -> Result in
print("原始数据2: \(response!)")
return .success("dyz_DataResponseSerializer_dyz")
}
SessionManager.default
.request(urlString)
.response { (response) in
print("原始数据1: \(response)")
}
.response(responseSerializer: dyzResponseSerilizer) { (dyzDataResponse) in
print("序列化之后:\(dyzDataResponse)")
}
- 点击
responseSerializer
-
responseSerializer.serializeResponse( self.request, self.response, self.delegate.data, self.delegate.error )
执行闭包,dyzResponseSerilizer初始化时候的闭包
extension DataRequest {
@discardableResult
public func response(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping (DataResponse) -> Void)
-> Self
{
delegate.queue.addOperation {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
var dataResponse = DataResponse(
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) }
}
return self
}
}
2、Data、String、JSON、Property List
SessionManager.default
.request(urlString)
.responseJSON { (response) in
print(response)
}
- 点击
responseJSON
extension DataRequest {
public static func jsonResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments)
-> DataResponseSerializer
{
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
}
}
@discardableResult
public func responseJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DataResponse) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.jsonResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
- 点击
serializeResponseJSON
extension Request {
public static func serializeResponseJSON(
options: JSONSerialization.ReadingOptions,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result
{
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) }
guard let validData = data, validData.count > 0 else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
}
do {
let json = try JSONSerialization.jsonObject(with: validData, options: options)
return .success(json)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
}
}
}