AFNetworking源码分析

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];
                });
            });
        });
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容