AlamofireiOS 进阶开发Swift开发进阶

Alamofire - Response

2019-08-24  本文已影响23人  Cooci_和谐学习_不急不躁

😊😊😊Alamofire专题目录,欢迎及时反馈交流 😊😊😊


Alamofire 目录直通车 --- 和谐学习,不急不躁!


Alamofire 请求数据之后,我们就会回调响应,但是底层是如何保证响应必然在请求之后的呢?以及 AlamofireResponse 到底是什么东西,这一篇详细讲解。

一、Response

1:response的执行顺序

首先我们先来看这段代码

SessionManager.default
    .request(urlString)
    .response { (response) in
        print(response)
    }

Alamofire 一个非常关键的类就是 Request ,请看下面这段代码是链式调用,但是怎么保证 responserequest 之后呢?

init(task: URLSessionTask?) {
    _task = task

    self.queue = {
        let operationQueue = OperationQueue()
        operationQueue.maxConcurrentOperationCount = 1
        operationQueue.isSuspended = true
        operationQueue.qualityOfService = .utility
        return operationQueue
    }()
}

2:response的作用

response 分为四种

这里可以看到并没有 upload 相关的,为什么?😕那是因为 upload 返回的就是普通数据,就没有必要重新封装。

其中 Default 开头就是返回原始数据,没有进过其他处理,不加 Default 可以通过序列化器处理!大家可以对比下面两个方法,不难得出结果

self.request = request
self.response = response
self.data = data
self.error = error
self.timeline = timeline

三、序列化器

就拿我们最熟悉的 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
    )
}
public static func jsonResponseSerializer(
    options: JSONSerialization.ReadingOptions = .allowFragments)
    -> DataResponseSerializer<Any>
{
    return DataResponseSerializer { _, response, data, error in
        return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
    }
}
    public static func serializeResponseJSON(
        options: JSONSerialization.ReadingOptions,
        response: HTTPURLResponse?,
        data: Data?,
        error: Error?)
        -> Result<Any>
    {
       // 省略了一些不重要的代码
        do {
            let json = try JSONSerialization.jsonObject(with: validData, options: options)
            return .success(json)
        } catch {
            return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
        }
    }

四、总结

非常高兴我们霸占了简书 RxSwift ,Alamofire 板块,只要搜索 RxSwift ,Alamofire 相关最新文章必然都是一些熟悉的身影~~~ 持续努力,变平凡为非凡 💪 💪 💪

就问此时此刻还有谁?45度仰望天空,该死!我这无处安放的魅力!

上一篇下一篇

猜你喜欢

热点阅读