😊😊😊Alamofire thematic directory. Welcome timely feedback and exchange

  • Alamofire (1) – URLSession prerequisite skill
  • Alamofire (2) — Background download
  • Alamofire (3) — Request
  • Alamofire (4) — Details you need to know
  • Alamofire (5) — Response
  • Alamofire (6) — Multiple form uploads
  • Alamofire (7) — Safety certification
  • Alamofire (8) — Final Chapter (Network Monitoring & Notifications & Downloader Packaging)

Alamofire Directory through train — Harmonious learning, not impatient!


After Alamofire requests the data, we call back the response, but how does the underlying guarantee that the response is necessarily after the request? And what exactly is Alamofire’s Response? This article explains it in detail.

A, the Response

1: execution sequence of response

Let’s look at this code first

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

One of Alamofire’s key classes is Request. See the following code for chained calls. How to ensure that response follows Request?

  • weresponseThe task is to join updelegate.queue.addOperation
  • Delivered to the main queue, after allresponseIt is provided to users externally, and users can directly perform OPERATIONS on the UI
  • And then go back out of the closure
init(task: URLSessionTask?). { _task = taskself.queue = {
        let operationQueue = OperationQueue()
        operationQueue.maxConcurrentOperationCount = 1
        operationQueue.isSuspended = true
        operationQueue.qualityOfService = .utility
        return operationQueue
    }()
}
Copy the code
  • The number of concurrent requests for this queue is 1
  • Initialization comes out of suspension by default

  • When the request is complete: The pending status of the queue is removed and the task can be executed normally
  • Tasks that have just been added to the queue can execute Soga sequentially when the request completes

2: The role of response

responseIs divided into four

  • DefaultDataResponse
  • DataResponse
  • DefaultDownloadResponse
  • DownloadResponse

It can be seen here that there is no upload related, why? πŸ˜• because the upload returned plain data, there was no need to rewrap it.

Where the Default start is to return the original data, no other processing, do not add Default can be processed through the serializer! You can compare the following two methods, it is not difficult to get the result

  • In fact, if you are careful, 😝😝 should be very easy to get, in fact, here encapsulationResponseAnd our traditionalResponseNot the same. In the packagingResponseIs a data storage model, in which to store external data needs
self.request = request
self.response = response
self.data = data
self.error = error
self.timeline = timeline
Copy the code

Serializers

Let’s take our most familiar JSON serializer and discuss it with you

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
    )
}
Copy the code
  • There’s one encapsulated hereresponseThe method of
  • The third argument is the initialization of the serializer
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)
    }
}
Copy the code
  • So this is what I’m going to returnDataResponseSerializerType serializer
  • The argument is a closure with a return value typeResult:Request.serializeResponseJSON
  • This is what we initialized up hereDataResponseSerializerCall to the argument closure of:DataRequest.jsonResponseSerializer(options: options)
    public static func serializeResponseJSON( options: JSONSerialization.ReadingOptions, response: HTTPURLResponse? , data: Data? , error: Error?)
        -> Result<Any>
    {
       // Omitted some unimportant code
        do {
            let json = try JSONSerialization.jsonObject(with: validData, options: options)
            return .success(json)
        } catch {
            return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
        }
    }
Copy the code
  • Very simple encapsulation validates some data
  • And then there’s the very familiarjsonSerializer:JSONSerialization.jsonObject
  • Returns the result of the serialization:.success(json)or.failure(error)

Four,

  • Create a serialization structure
  • Through serialization structure-initiate serialization response closure
  • Make the outside worldtaskDelegateThe data inside -> passes to our external closure – is given to our custom sequence or serializer implementation that the system implements for us
  • responseValidation –response.statusCodeJudge – issueresult
  • resultThat’s the return value of our serializer
  • synchronousoperation 把 resulttoresponseThe structure of the body
  • data/downloadResponseTo store data
  • The response callbackreturnResponse Response data

Very happy that we occupy nuggets RxSwift,Alamofire plate, as long as the search for RxSwift,Alamofire related to the latest articles are bound to be some familiar figures ~~~ continue efforts to change ordinary into extraordinary πŸ’ͺ πŸ’ͺ πŸ’ͺ

Just ask who else is there right now? 45 degrees up in the sky, damn it! My charm with no place to put it!