Alamofire-DataRequest流程解析

2019-08-20  本文已影响0人  SPIREJ
SessionManager类dataRequest.jpeg

Alamofire有四种RequestTask任务类型,如下

enum RequestTask {
    case data(TaskConvertible?, URLSessionTask?)
    case download(TaskConvertible?, URLSessionTask?)
    case upload(TaskConvertible?, URLSessionTask?)
    case stream(TaskConvertible?, URLSessionTask?)
}

这里主要分析下DataRequest的流程

首先使用Alamofirerequest非常简单

SessionManager.default.request(urlStr, method: .get, parameters: nil)
            .response { (response) in
                debugPrint(response)
        }
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)
    }
}

///------------分割线-------------///

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)
    }
}
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)判断是否有参数
(2) HTTPMethod判断
GET: 百分比编码+拼接'&'
query方法这里面有递归取URL中的参数,并且拼接上&符,注意joined方法最后一个元素不拼接&
components.map { "\($0)=\($1)" }.joined(separator: "&")

POST:
(1)Content-Type
(2)urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false)

open func resume() {
    guard let task = task else { delegate.queue.isSuspended = false ; return }

    if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }

    task.resume()

    NotificationCenter.default.post(
        name: Notification.Name.Task.DidResume,
        object: self,
        userInfo: [Notification.Key.Task: task]
    )
}

总结

上面就是Alamofire - DataRequest的基本流程,其他三种downloaduploadstream基本类似,只是在request初始化的时候根据RequestTask创建不同类型的taskDelegate

就是把Request的代理移交给SessionDelegate,网络请求的代理回调到时候还是去SessionDelegate里面处理了具体的代理回调事务!

上一篇 下一篇

猜你喜欢

热点阅读