preface
Alamofire was refactoring in 5.0 and has not been released yet. The analysis below is based on version 5.0.0-RC.3
The problem
Before you get into the text, here are a few questions that I hope you’ll be able to answer by the end of this passage.
- Session, SessionDelegate, Request?
let urlString = "https://api.apiopen.top/getJoke? page=1&count=2&type=text"
let request = AF.request(urlString).responseJSON { (resp) in
print(resp)} / / assume the request will be back after 3 seconds DispatchQueue. Main. AsyncAfter (deadline: now () + 10) {request. ResponseJSON {(resp)in
print(resp)
}
}
Copy the code
- When was the DataTask created? What was the DataTask sent?
- After the request comes back, set the response several times. Can you call back?
- What’s going on in responseJSON?
The main class or protocol diagram in Alamofire
Session, SessionDelegate, Request, and RequestDelegate properties are described
The Session attributes:
- Let session: URLSession, system URLSession, used to create tasks
- Let delegate: SessionDelegate, the session delegate that handles various callbacks for requests
- Let startRequestsImmediately: Bool, whether the request immediately
- Let rootQueue: DispatchQueue, queue on which internal callbacks and status updates are placed, must be serial queues
- Let requestQueue: DispatchQueue, create a Request queue, default is a serial queue whose target is rootQueue
- Let serializationQueue: DispatchQueue, the queue in which Response data is deserialized. The default is a serial queue whose target is rootQueue
- let interceptor: RequestInterceptor? , a request interceptor, which is a merging of the RequestAdapter and RequestRetrier, is used to modify the request retry policy before sending the request and after the request fails
- let serverTrustManager: ServerTrustManager? , safety certification manager
- let redirectHandler: RedirectHandler? , redirect the callback
- let cachedResponseHandler: CachedResponseHandler? , cache back
- Let eventMonitor: CompositeEventMonitor, event listener
- Var requestTaskMap: requestTaskMap, used to hold the task, the request and the status of a task
- Var activeRequests:Set = [], for all activeRequests
SessionDelegate attributes:
- Private let fileManager: fileManager is used to process files in the callback for download
- weak var stateProvider: SessionStateProvider? To obtain request information from the URLSessionDelegate and to call back to the outside state
- var eventMonitor: EventMonitor? In various callbacks, call the method corresponding to the event listener and let the outside world handle it
The SessionStateProvider protocol defines the following methods:
- var serverTrustManager: ServerTrustManager? {get} Obtain security certification administrator
- var redirectHandler: RedirectHandler? {get} Gets the handler of the redirection
- var cachedResponseHandler: CachedResponseHandler? {get} The handler that gets the cached response
- func request(for task: URLSessionTask) -> Request? Obtain requests from task
- Func didGatherMetricsForTask(_ Task: URLSessionTask) Callback after performance indicators have been collected
- Func didCompleteTask(_ Task: URLSessionTask) Callback to request completion
- func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? Get the certificate for authentication
- func cancelRequestsForSessionInvalidation(with error: Error?) , URLSession invalid callback
The Request attributes:
- Let underlyingQueue: DispatchQueue, an asynchronous serial queue of internal callbacks
- Let serializationQueue: DispatchQueue, which is the queue of the serialization, same as Session
- let eventMonitor: EventMonitor? , event listener, same as Session
- let interceptor: RequestInterceptor? , request interceptor, same as Session
- weak var delegate: RequestDelegate? , requestDelegate
- ProtectedMutableState: Protector, which stores various information about the request
- State of the state
- UploadProgressHandler upload progress callback
- DownloadProgressHandler specifies the download progress callback
- RedirectHandler Callback for redirection
- CachedResponseHandler Callback to the cache
- CURLHandler, a callback to curl
- ResponseSerializers, collection of response serials
- A collection of responseSerializerCompletions, serialization response callback
- Requests, all requests are currently requested
- Tasks: All tasks are currently requested
- Metrics, all metrics currently requested
- RetryCount: indicates the number of retries
- The error message
- All other properties depend indirectly or this time on protectedMutableState
The RequestDelegate protocol defines methods:
- Var sessionConfiguration: URLSessionConfiguration {get} to obtain Session configuration
- Var startImmediately: Bool {get}, whether to send the request immediately
- Func cleanup(after request: request), cleanup of the request
- Func retryResult(for Request: Request, dueTo Error: AFError, Completion: @escaping (retryResult) -> Void), asks the agent if it needs to retry
- func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) , tells the agent how long to retry
Session, SessionDelegate, and Request
- Session. Delegate and URLSession. Delegate both point to the instance of SessionDelegate
- Session. Delegate points to the SessionDelegate in order to hold it and not to release it, and URLSession. Delegate points to it in order to execute various callbacks to URLSession and URLSessionTask
- SessionDelegate stateProvider will point to the Session
- When the session. request method is called, the request is created and put into session.activerequests
- Request. Delegate points to Session
Request creation flowchart
Follow this flow chart to answer the questions above
- DataTask is in
Session.didCreateURLRequest
Since the Request is created, the internal operations of both Request and response functions are asynchronous, and the execution order cannot be determined, so the Request may be sent in one of the following two placesSession.updateStatesForTask
And the second is inRequest. Resume function
- After the request comes back, the response is set several more times, and as you can see from the flowchart above, the callback is invoked directly
- In response, in addition to the things in the flowchart, data will be deserialized to the corresponding format before the callback is executed. If the serialization fails, the proxy will be called to ask whether it needs to retry; if the deserialization succeeds, the callback will be called