Alamofire源码分析(5)——TaskDelegate

在上一次分析task中提到TaskDelegate,现在就来详细看看它做了什么:

  1. Request初始化时,通过枚举任务类型创建对应任务代理进行下发任务:
open class Request {
    ...
    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() }//记录时间
    }
    ...
}
  1. DataTaskDelegateDownloadTaskDelegateUploadTaskDelegate都继承了TaskDelegate类(TaskDelegate是一个NSObject类),然后不同的任务类型实现的Delegate也不同):
class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
    ...
    func urlSession(
        _ session: URLSession,
        dataTask: URLSessionDataTask,
        didReceive response: URLResponse,
        completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { ... }

    func urlSession(
        _ session: URLSession,
        dataTask: URLSessionDataTask,
        didBecome downloadTask: URLSessionDownloadTask) { ... }

    func urlSession(
        _ session: URLSession, 
        dataTask: URLSessionDataTask, 
        didReceive data: Data) { ... }

    func urlSession(
        _ session: URLSession,
        dataTask: URLSessionDataTask,
        willCacheResponse proposedResponse: CachedURLResponse,
        completionHandler: @escaping (CachedURLResponse?) -> Void) { ... }
}

class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { 
    ...
    func urlSession(
        _ session: URLSession,
        downloadTask: URLSessionDownloadTask,
        didFinishDownloadingTo location: URL) { ... }

    func urlSession(
        _ session: URLSession,
        downloadTask: URLSessionDownloadTask,
        didWriteData bytesWritten: Int64,
        totalBytesWritten: Int64,
        totalBytesExpectedToWrite: Int64) { ... }

    func urlSession(
        _ session: URLSession,
        downloadTask: URLSessionDownloadTask,
        didResumeAtOffset fileOffset: Int64,
        expectedTotalBytes: Int64) { ... }
    ...
}

class UploadTaskDelegate: DataTaskDelegate {
    ...
    func URLSession(
        _ session: URLSession,
        task: URLSessionTask,
        didSendBodyData bytesSent: Int64,
        totalBytesSent: Int64,
        totalBytesExpectedToSend: Int64) { ... }
}
  1. 在分析SessionManager那一层的时候,我们看到了代理移交,所以当数据回来时会来到相应协议:
代理移交
extension SessionDelegate: URLSessionTaskDelegate {
    ...
    open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {

        let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in
            guard let strongSelf = self else { return }

            strongSelf.taskDidComplete?(session, task, error)
            //调用TaskDelegate的方法
            strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error)
            ...
            strongSelf[task] = nil  //解除关联
        }
        ...
    }
}

通过strongSelf[task]获取对应Request,再拿到TaskDelegate调用方法进行一些后续处理:

delegate就是TaskDelegate
后续处理

分析到这一层可以理解为,产品经理(SessionManager)把任务交给组长(Request),组长把具体需求分发给各职能的组员(TaskDelegate)。而组员如何落实需求,产品经理是不知道的,产品经理只知道结果,这样一个管理过程是非常清晰的。

下一篇分析数据处理response。

你可能感兴趣的:(Alamofire源码分析(5)——TaskDelegate)