阅读 43

Alamofire(二) Request流程及源码解析

前言

这篇文章主要是对Alamofire的重要模块-Request进行探索和分析,以及总结整个request的过程及源码解析。

Request初探

我们先写如下代码:这是一个简单的使用Alamofire进行网络请求的示例

SessionManager.default.request(myGetUrlString, method: .get, parameters: ["array":getJsonFromArray(array)])
            .response { (response) in
                debugPrint(response)
        }
复制代码

老规矩,点进去探索,根据注释知道这里返回的是一个DataRequest,第一步是初始一个URLRequest类型的originalRequest

/// - returns: The created `DataRequest`.
    @discardableResult
    open func request(
        _ url: URLConvertible,
        method: HTTPMethod = .get,
        parameters: Parameters? = nil,
        encoding: ParameterEncoding = URLEncoding.default,
        headers: HTTPHeaders? = nil)
        -> DataRequest
    {
        var originalRequest: URLRequest?

        do {
            originalRequest = try URLRequest(url: url, method: method, headers: headers)
            let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters)
            return request(encodedURLRequest)
        } catch {
            return request(originalRequest, failedWith: error)
        }
    }
复制代码

点进去看看try encoding.encode做了什么,由于看到默认类型是URLEncoding,所以我们这里点进去URLEncoding.encode方法查看一下

image

  /// - returns: The encoded request.
    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = try urlRequest.asURLRequest()

        guard let parameters = parameters else { return urlRequest }

        if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) {
            guard let url = urlRequest.url else {
                throw AFError.parameterEncodingFailed(reason: .missingURL)
            }

            if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
                let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
                urlComponents.percentEncodedQuery = percentEncodedQuery
                urlRequest.url = urlComponents.url
            }
        } else {
            if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
                urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
            }

            urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false)
        }

        return urlRequest
    }
复制代码

总结一下上面的代码都做了什么:

  1. .get, .head, .delete 这三个请求方式是直接把请求参数拼接到URL上(点进encodesParametersInURL(with: method)可以知道是这三个方式),其他请求方式是把参数丢到httpBody里。

  2. 对URL进行百分号编码(和Url编码同义),在这里可以看出,前半段是对URL进行百分号编码,后半段query(parameters)是对参数进行百分号编码

     let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
复制代码

点进query(parameters),可以看到这里对参数进行了排序处理,然后还把每个key value遍历出来组成元组,然后return的时候再把参数拼接起来

private func query(_ parameters: [String: Any]) -> String {
        var components: [(String, String)] = []

        for key in parameters.keys.sorted(by: <) {
            let value = parameters[key]!
            components += queryComponents(fromKey: key, value: value)
        }
        return components.map { "\($0)=\($1)" }.joined(separator: "&")
    }
复制代码

了解完encoding里面到底做了什么,这时回到最外层的request 方法

open func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
        var originalRequest: URLRequest?

        do {
            originalRequest = try urlRequest.asURLRequest()
            let originalTask = DataRequest.Requestable(urlRequest: originalRequest!)

            let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
            let request = DataRequest(session: session, requestTask: .data(originalTask, task))

            delegate[task] = request

            if startRequestsImmediately { request.resume() }

            return request
        } catch {
            return request(originalRequest, failedWith: error)
        }
    }
复制代码

一步步分析:

  1. originalTaskDataRequest里一个具有taks方法的结构体
open class DataRequest: Request {

    // MARK: Helper Types

    struct Requestable: TaskConvertible {
        let urlRequest: URLRequest

        func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
            do {
                let urlRequest = try self.urlRequest.adapt(using: adapter)
                return queue.sync { session.dataTask(with: urlRequest) }
            } catch {
                throw AdaptError(error: error)
            }
        }
    }
}
复制代码
  1. let task = try originalTask.task(session: session, adapter: adapter, queue: queue) 初始化里面的task方法,返回的是一个URLSessionTask类型

  2. let request = DataRequest(session: session, requestTask: .data(originalTask, task)) 调用了DataRequest里的init初始方法, 如下,走的是.data,所以这里初始化了当前的taskDelegate方法,还给当前的originalTask赋值

    init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
        self.session = session

        switch requestTask {
        case .data(let originalTask, let task):
            taskDelegate = DataTaskDelegate(task: task)
            self.originalTask = originalTask
        case .download(let originalTask, let task):
            taskDelegate = DownloadTaskDelegate(task: task)
            self.originalTask = originalTask
        case .upload(let originalTask, let task):
            taskDelegate = UploadTaskDelegate(task: task)
            self.originalTask = originalTask
        case .stream(let originalTask, let task):
            taskDelegate = TaskDelegate(task: task)
            self.originalTask = originalTask
        }

        delegate.error = error
        delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
    }
复制代码
  • 那么delegate.queue.addOperation干了什么呢?
  • 点进去跟踪queue,发现它是在TaskDelegate里,它是一个OperationQueue
  • 它里面有一个重要的属性isSuspended,说明在TaskDelegate初始化的时候,这个queue就是挂起状态,猜测是发送网络请求时,先挂起,然后等到接收到response再取消挂起,正常接收响应,那么继续验证一下猜想
init(task: URLSessionTask?) {
        _task = task

        self.queue = {
            let operationQueue = OperationQueue()

            operationQueue.maxConcurrentOperationCount = 1
            operationQueue.isSuspended = true
            operationQueue.qualityOfService = .utility

            return operationQueue
        }()
    }
复制代码
  1. 回到外界,delegate[task] = request,这里就是给当前的SessionDelegate添加一个获得请求响应的能力
  • requst的初始化我们已经看完了,那么是如何把它串起来的呢? 我们知道URLSession的请求完成回调方法是didCompleteWithError,果然我们在TaskDelegate里能找到这个代理方法
     @objc(URLSession:task:didCompleteWithError:)
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if let taskDidCompleteWithError = taskDidCompleteWithError {
            taskDidCompleteWithError(session, task, error)
        } else {
            if let error = error {
                if self.error == nil { self.error = error }

                if
                    let downloadDelegate = self as? DownloadTaskDelegate,
                    let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data
                {
                    downloadDelegate.resumeData = resumeData
                }
            }

            queue.isSuspended = false
        }
    }
复制代码

重点在这里queue.isSuspended = false,还记得我们前面的猜想,是在请求的时候挂起,然后请求完毕的时候取消挂起,猜想得到验证。 那么看看请求是怎么样回调到完成的呢? 我们知道SessionDelegate是一个集合了所有代理的类,所以这里strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error)执行了TaskDelegate里的这个方法,就是上面刚刚看到的

open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        /// Executed after it is determined that the request is not going to be retried
        let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in
            guard let strongSelf = self else { return }

            strongSelf.taskDidComplete?(session, task, error)

            strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error)

            var userInfo: [String: Any] = [Notification.Key.Task: task]

            if let data = (strongSelf[task]?.delegate as? DataTaskDelegate)?.data {
                userInfo[Notification.Key.ResponseData] = data
            }

            NotificationCenter.default.post(
                name: Notification.Name.Task.DidComplete,
                object: strongSelf,
                userInfo: userInfo
            )

            strongSelf[task] = nil
        }

        guard let request = self[task], let sessionManager = sessionManager else {
            completeTask(session, task, error)
            return
        }

        // Run all validations on the request before checking if an error occurred
        request.validations.forEach { $0() }

        // Determine whether an error has occurred
        var error: Error? = error

        if request.delegate.error != nil {
            error = request.delegate.error
        }

        /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request
        /// should be retried. Otherwise, complete the task by notifying the task delegate.
        if let retrier = retrier, let error = error {
            retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in
                guard shouldRetry else { completeTask(session, task, error) ; return }

                DispatchQueue.utility.after(timeDelay) { [weak self] in
                    guard let strongSelf = self else { return }

                    let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false

                    if retrySucceeded, let task = request.task {
                        strongSelf[task] = request
                        return
                    } else {
                        completeTask(session, task, error)
                    }
                }
            }
        } else {
            completeTask(session, task, error)
        }
    }
复制代码

总结

image

  1. **SessionDelegate负责拿到所有代理事件,然后分发给DataTaskDelegate**处理所需要的代理事件
  2. 通过delegate[task] = requestSessionDelegate获得接收到响应的能力
  3. 通过queue.isSuspended来做获得响应前的阻塞
  4. SessionManager调起RequestRequest给具体的dataRequest下发任务,执行完任务通过SessionDelegate再回调出来给DataTaskDelegate
关注下面的标签,发现更多相似文章
评论