美文网首页iOS学习iOS程序猿
AFNetworking源码分析

AFNetworking源码分析

作者: sea777777 | 来源:发表于2016-10-20 14:30 被阅读226次

    AFNetworking 实现了文件的上传/下载,以及断点续传。
    内部封装了 NSURLSession ,替代了之前的 NSURLConnection。

    关于断点续传:把下载文件放到temp里,每间隔一段时间并用文件的形式存储下载完的数据字节数,当resume的时候,会查询到之前下载到进度,如1000字节,并放在HTTP 头部的 range 字段,如:1000-3000,这样服务器就会返回1000字节后的数据;断点上传道理类似;

    AFURLSessionManager 会创建并管理一个NSURLSession 对象,这是一次会话,而这个会话可以创建多个task任务,每个任务可以执行上传下载等操作;

    依赖的包有:

    • Security.framework
    • MobileCoreServices.framework
    • SystemConfiguration.framework
    • UIKit.framework

    对于 NSURLSessionDataTask,官方解释说,这没有其他任何的附加功能,只是为了区别和上传下载的字面意思。但是这个任务可以用来请求一些html页面等等;

    
    
    // 创建session配置:如 认证机制,缓存,cookies存储位置,超时时间等...
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        
        NSURL *URL = [NSURL URLWithString:@"http://123.125.110.24/imtt.dd.qq.com/16891/97EF88D9A32972CDE911B374A46B774D.apk?mkey=58070789ffa35a8e&f=4e1d&c=0&fsname=com.tencent.WeFire_2.7.0_5477.apk&p=.apk"];
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        
        //创建downloadtask
        //progress:进度信息,会不断进行回调
        //destination:指定下载完的文件存储位置
        //completionHandler:执行完毕回调
        _downloadTask = [manager downloadTaskWithRequest:request
                                                                         progress:^(NSProgress *downloadProgress)
        {
            NSLog(@"downloadProgress:%f",downloadProgress.fractionCompleted);
        }
                                                                      destination:^ NSURL *(NSURL *targetPath, NSURLResponse *response)
        {
            
            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                                                  inDomain:NSUserDomainMask
                                                                         appropriateForURL:nil
                                                                                    create:NO
                                                                                     error:nil];
            
            return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
            
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            NSLog(@"File downloaded to: %@", filePath);
        }];
        
        // 开启任务,必须调用,否则不执行
        [_downloadTask resume];
        
        //挂起任务
    // [_downloadTask suspend];
    
    
    
    
    // 创建 downloadTask ,并给 downloadTask 添加代理
    - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
                                                 progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
                                              destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                                        completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
    {
        __block NSURLSessionDownloadTask *downloadTask = nil;
        
        //创建下载任务;
        //在修复bug之前,异步执行任务,修复bug后直接执行 block
        url_session_manager_create_task_safely(^{
            downloadTask = [self.session downloadTaskWithRequest:request];
        });
        
        //为 task 添加代理,此代理为 task 执行以下操作:进度处理,目标文件处理回调,处理完成回调;
        [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
    
        return downloadTask;
    }
    
    

    AFURLSessionManagerTaskDelegate:
    这个类的作用就是为 downloadTask 服务,如进度回调/设置文件最终存储位置/执行任务完成回调(completionHandler)/恢复下载/挂起任务

    
    
    - (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask
                              progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
                           destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                     completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
    {
        AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
        //设置代理需要服务的对象:SessionManager
        delegate.manager = self;
        //代理为 task 执行‘完成回调’blok
        delegate.completionHandler = completionHandler;
        
        if (destination) {
            // 重新封装 destination ,根据 destination 返回url再把文件转到这个url(这个session参数没用到???);
            delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session,
                                                                  NSURLSessionDownloadTask *task,
                                                                  NSURL *location)
            {
                return destination(location, task.response);
            };
        }
        
        downloadTask.taskDescription = self.taskDescriptionForSessionTasks;
        
        //添加代理 ,delegate 处理进度
        [self setDelegate:delegate forTask:downloadTask];
        
        //设置进度回调
        delegate.downloadProgressBlock = downloadProgressBlock;
    }
    
    
    
    //存储 delegate,并设置 Progress 属性 以及相关回调
    - (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
                forTask:(NSURLSessionTask *)task
    {
        NSParameterAssert(task);
        NSParameterAssert(delegate);
        
        /*
         sessionManager 可以创建多个任务,是1对多点关系
         所以同时添加多个task的时候,下面操作可能会导致线程不安全,需要加锁;
         */
        [self.lock lock];
        // sessionManager 把taskDelegate 以字典方式存储 key:delegate唯一标识 value:delegate
        self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
        
        //设置 progress 相关属性和操作
        [delegate setupProgressForTask:task];
        [self addNotificationObserverForTask:task];
        [self.lock unlock];
    }
    
    
    
    
    
    /**
     uploadProgress downloadProgress 负责存储进度属性以及task相关操作:
     设置uploadProgress 和 downloadProgress 取消操作 暂停操作 恢复下载上传
     监听 uploadProgress / downloadProgress
     */
    - (void)setupProgressForTask:(NSURLSessionTask *)task {
        __weak __typeof__(task) weakTask = task;
    
        //获取下载或者上传任务的总字节数大小;用来计算当前进度(ios7之前步兼容,iOS (7.0 and later))
        self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
        self.downloadProgress.totalUnitCount = task.countOfBytesExpectedToReceive;
        
        //允许取消 task
        [self.uploadProgress setCancellable:YES];
        
        //取消回调,需把task转成strong,以保证再task在取消前不被释放掉
        [self.uploadProgress setCancellationHandler:^{
            __typeof__(weakTask) strongTask = weakTask;
            [strongTask cancel];
        }];
        
        //允许暂停,以下设置类似取消操作
        [self.uploadProgress setPausable:YES];
        [self.uploadProgress setPausingHandler:^{
            __typeof__(weakTask) strongTask = weakTask;
            [strongTask suspend];
        }];
        
        //恢复上传
        if ([self.uploadProgress respondsToSelector:@selector(setResumingHandler:)]) {
            [self.uploadProgress setResumingHandler:^{
                __typeof__(weakTask) strongTask = weakTask;
                [strongTask resume];
            }];
        }
    
        [self.downloadProgress setCancellable:YES];
        [self.downloadProgress setCancellationHandler:^{
            __typeof__(weakTask) strongTask = weakTask;
            [strongTask cancel];
        }];
        [self.downloadProgress setPausable:YES];
        [self.downloadProgress setPausingHandler:^{
            __typeof__(weakTask) strongTask = weakTask;
            [strongTask suspend];
        }];
    
        if ([self.downloadProgress respondsToSelector:@selector(setResumingHandler:)]) {
            [self.downloadProgress setResumingHandler:^{
                __typeof__(weakTask) strongTask = weakTask;
                [strongTask resume];
            }];
        }
        
        /** 监听下载 uploadProgress downloadProgress 的 fractionCompleted(百分比) 属性
            实际上修改 downloadProgress/uploadProgress 的 totalUnitCount 或者 completedUnitCount 属性
            就会自动计算 fractionCompleted 的值;
            所以在回调中直接取 fractionCompleted 即可;
         */
        [self.downloadProgress addObserver:self
                                forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
                                   options:NSKeyValueObservingOptionNew
                                   context:NULL];
        [self.uploadProgress addObserver:self
                              forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
                                 options:NSKeyValueObservingOptionNew
                                 context:NULL];
    }
    
    
    
    
    //添加监听resume 和suspend,以便接收delegate发送的通知
    - (void)addNotificationObserverForTask:(NSURLSessionTask *)task {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task];
    }
    
    
    

    需要实现几个代理:

    • NSURLSessionDelegate,
    • NSURLSessionTaskDelegate,
    • NSURLSessionDataDelegate,
    • NSURLSessionDownloadDelegate

    这个方法很关键,用于累加返回的data数据:

    
    /**
     更新下载进度:
     下载过程会多次调用这个方法
     每次调用会接收一段数据
     totalBytesWritten:到目前为止接收到的数据总大小(累计接收到的数据);
     totalBytesExpectedToWrite:总的下载数据大小;
     totalBytesWritten/totalBytesExpectedToWrite:已完成进度百分比;
     */
    - (void)URLSession:(NSURLSession *)session
          downloadTask:(NSURLSessionDownloadTask *)downloadTask
          didWriteData:(int64_t)bytesWritten
     totalBytesWritten:(int64_t)totalBytesWritten
    totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
    {
        
        AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
        
        // 传递给代理,记录下载进度
        if (delegate) {
            [delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
        }
    
        if (self.downloadTaskDidWriteData) {
            self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
        }
    }
    
    
    
    
    // 下载完成回调
    - (void)URLSession:(NSURLSession *)session
          downloadTask:(NSURLSessionDownloadTask *)downloadTask
    didFinishDownloadingToURL:(NSURL *)location
    {
        AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
        
        // 调用setDownloadTaskDidFinishDownloadingBlock方法才会初始化downloadTaskDidFinishDownloading
        // 否则会在delegate里移动下载文件到指定位置
        if (self.downloadTaskDidFinishDownloading) {
            // 获取用户指定下载路径
            NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
            if (fileURL) {
                delegate.downloadFileURL = fileURL;
                NSError *error = nil;
                //移动文件到指定位置
                [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error];
                
                //只看到发送错误信息通知,未找到在哪处理错误信息
                if (error) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
                }
    
                return;
            }
        }
        
        // 通知 delegate 把下载的临时文件转移到指定地点
        if (delegate) {
            [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location];
        }
    }
    
    
    
    
    
    // sessionTaskDelegate
    // 完成传输任务
    - (void)URLSession:(NSURLSession *)session
                  task:(NSURLSessionTask *)task
    didCompleteWithError:(NSError *)error
    {
        AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
    
        // delegate may be nil when completing a task in the background
        if (delegate) {
            [delegate URLSession:session task:task didCompleteWithError:error];
    
            // 移除代理以及监听
            [self removeDelegateForTask:task];
        }
    
        // 需要手动调用 setTaskDidCompleteBlock ,才会执行 taskDidComplete,如果没有手动设置,则在代理里执行commectionHandler
        if (self.taskDidComplete) {
            self.taskDidComplete(session, task, error);
        }
    }
    
    

    相应的会调用delegate中的几个方法,主要用delegate来辅助执行:

    
    
    
    - (void)URLSession:(__unused NSURLSession *)session
              dataTask:(__unused NSURLSessionDataTask *)dataTask
        didReceiveData:(NSData *)data
    {
        self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived;
        self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive;
    
        [self.mutableData appendData:data];
    }
    
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
       didSendBodyData:(int64_t)bytesSent
        totalBytesSent:(int64_t)totalBytesSent
    totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
        
        self.uploadProgress.completedUnitCount = task.countOfBytesSent;
        self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
    }
    
    #pragma mark - NSURLSessionDownloadDelegate
    
    //用于记录下载进度:
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
          didWriteData:(int64_t)bytesWritten
     totalBytesWritten:(int64_t)totalBytesWritten
    totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
        
        self.downloadProgress.totalUnitCount = totalBytesExpectedToWrite;
        self.downloadProgress.completedUnitCount = totalBytesWritten;
    }
    
    //用于记录下载进度:
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
     didResumeAtOffset:(int64_t)fileOffset
    expectedTotalBytes:(int64_t)expectedTotalBytes{
        self.downloadProgress.totalUnitCount = expectedTotalBytes;
        self.downloadProgress.completedUnitCount = fileOffset;
    }
    
    //下载完成回调
    - (void)URLSession:(NSURLSession *)session
          downloadTask:(NSURLSessionDownloadTask *)downloadTask
    didFinishDownloadingToURL:(NSURL *)location
    {
        NSError *fileManagerError = nil;
        self.downloadFileURL = nil;
    
        // 把下载到临时文件移动到指定地点
        if (self.downloadTaskDidFinishDownloading) {
            
            // 获取用户指定的目标 url
            self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
            if (self.downloadFileURL) {
                [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError];
    
                //只看到发送错误信息通知,未找到在哪处理错误信息
                if (fileManagerError) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
                }
            }
        }
    }
    
    

    最后一步,执行completionHandler:
    completionHandler 交给 delegate 来处理:

    
    
    
    /**
     下载完成回调
     执行 complectionHandler 
     并把返回结果打包发送通知
     */
    - (void)URLSession:(__unused NSURLSession *)session
                  task:(NSURLSessionTask *)task
    didCompleteWithError:(NSError *)error
    {
        
        // 执行重要操作之前需要把 weak 类型转成 strong,防止过程中 manager 被释放
        __strong AFURLSessionManager *manager = self.manager;
        
        __block id responseObject = nil;
        
        __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
        userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
    
        //Performance Improvement from #2672
        NSData *data = nil;
        // 把 mutableData(累计下载完的数据)拷贝到data,然后释放
        if (self.mutableData) {
            data = [self.mutableData copy];
            //We no longer need the reference, so nil it out to gain back some memory.
            self.mutableData = nil;
        }
    
        /**在didFinishDownloadingToURL 回调里已经记录了 downloadFileURL 变量
         优先记录 downloadFileURL 其次记录data,因为存储url数据量小
         */
        if (self.downloadFileURL) {
            userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
        } else if (data) {
            userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
        }
    
        //如果下载出错,则 执行completionHandler block的时候传递错误信息
        if (error) {
            userInfo[AFNetworkingTaskDidCompleteErrorKey] = error;
    
            dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
                if (self.completionHandler) {
                    self.completionHandler(task.response, responseObject, error);
                }
    
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
                });
            });
        } else {
            dispatch_async(url_session_manager_processing_queue(), ^{
                NSError *serializationError = nil;
                
                /** 解密 data 数据 
                    task.response:存储:url 类型 长度 文件名 加密信息
                 */
                responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError];
    
                // 如果下载数据成功,即 downloadFileURL 不为空,优先使用 url ,如果没有 url,再使用 responseObject
                if (self.downloadFileURL) {
                    responseObject = self.downloadFileURL;
                }
                
                if (responseObject) {
                    userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
                }
    
                if (serializationError) {
                    userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
                }
    
                /**
                 把任务添加到 completionQueue 中;
                 并发执行
                 */
                dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
                    
                    // 执行 completionHandler ,传递解密后的数据,或者url ,以及错误信息
                    if (self.completionHandler) {
                        self.completionHandler(task.response, responseObject, serializationError);
                    }
                    
                    // 把数据打包发送通知,用于用户自己扩展
                    // 例如下载操作和 completionHandler 不在一个类中,可以接收这个通知
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
                    });
                });
            });
        }
    }
    
    

    相关文章

      网友评论

        本文标题:AFNetworking源码分析

        本文链接:https://www.haomeiwen.com/subject/pwvfuttx.html