該文章閱讀的AFNetworking的版本爲3.2.0。git
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
複製代碼
在AFHTTPSessionManager
類中全部的初始化方法最終都會調用到- (instancetype)initWithBaseURL:(NSURL *)url sessionConfiguration:(NSURLSessionConfiguration *)configuration
方法中github
- (instancetype)initWithBaseURL:(NSURL *)url
sessionConfiguration:(NSURLSessionConfiguration *)configuration
{
// 首先調用了父類AFURLSessionManager的初始化方法
self = [super initWithSessionConfiguration:configuration];
if (!self) {
return nil;
}
// 若是有效的url後沒有正斜線「/」就添加上正斜線「/」
if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
url = [url URLByAppendingPathComponent:@""];
}
// 記錄url
self.baseURL = url;
// 實例化請求和響應序列化對象
self.requestSerializer = [AFHTTPRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializer];
return self;
}
複製代碼
在其父類AFURLSessionManager
類中的- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration
中作了基本屬性的初始化數組
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
self = [super init];
if (!self) {
return nil;
}
// 初始化NSURLSessionConfiguration若是沒有傳則用默認
if (!configuration) {
configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
}
self.sessionConfiguration = configuration;
// 初始化一個操做隊列並設置最大線程併發數爲1
self.operationQueue = [[NSOperationQueue alloc] init];
self.operationQueue.maxConcurrentOperationCount = 1;
// 利用已經初始化好的NSURLSessionConfiguration和NSOperationQueue初始化NSURLSession並遵照了代理
self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];
// 初始化JSON響應序列對象
self.responseSerializer = [AFJSONResponseSerializer serializer];
// 初始化安全策略
self.securityPolicy = [AFSecurityPolicy defaultPolicy];
// 初始化網絡狀態監測對象
#if !TARGET_OS_WATCH
self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
#endif
// 初始化可變字典保存NSURLSessionTask和其對應的delegate,並以NSURLSessionTask的屬性taskIdentifier作key,以NSURLSession的delegate作value
self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];
// 初始化self.mutableTaskDelegatesKeyedByTaskIdentifier可變字典的鎖,確保字典在多線程訪問時的線程安全
self.lock = [[NSLock alloc] init];
self.lock.name = AFURLSessionManagerLockName;
// 異步的獲取當前session的全部未完成的task,並進行置空處理,主要是爲了從後臺切換到前臺時從新初始化session
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
for (NSURLSessionDataTask *task in dataTasks) {
[self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil];
}
for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
[self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil];
}
for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
[self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil];
}
}];
return self;
}
複製代碼
以GET請求爲例安全
[manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"下載進度:%@", downloadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"響應對象:%@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"錯誤:%@", error);
}];
複製代碼
點擊進入方法中bash
- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters
progress:(void (^)(NSProgress * _Nonnull))downloadProgress
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
// 生成一個NSURLSessionDataTask對象
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
URLString:URLString
parameters:parameters
uploadProgress:nil
downloadProgress:downloadProgress
success:success
failure:failure];
// 開始任務
[dataTask resume];
return dataTask;
}
複製代碼
發現全部的請求方法不管是GET、POST仍是其餘都調用了同一個方法服務器
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
success:(void (^)(NSURLSessionDataTask *, id))success
failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
// 把全部的參數解析拼接生成一個NSMutableURLRequest對象,若是沒法解析則回調返回錯誤
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
return nil;
}
// 用生成的NSMutableURLRequest對象生成一個NSURLSessionDataTask對象並回調成功或失敗
__block NSURLSessionDataTask *dataTask = nil;
dataTask = [self dataTaskWithRequest:request
uploadProgress:uploadProgress
downloadProgress:downloadProgress
completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) {
if (failure) {
failure(dataTask, error);
}
} else {
if (success) {
success(dataTask, responseObject);
}
}
}];
return dataTask;
}
複製代碼
先看在AFURLRequestSerialization
類中如何利用各類參數生成NSMutableURLRequest
對象網絡
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
// 在debug模式下若是缺乏參數則會crash
NSParameterAssert(method);
NSParameterAssert(URLString);
NSURL *url = [NSURL URLWithString:URLString];
NSParameterAssert(url);
// 生成NSMutableURLRequest對象並設置請求方式
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
mutableRequest.HTTPMethod = method;
// 遍歷AFHTTPRequestSerializer的各個屬性
for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
// 若是發現有正在被觀察的屬性
if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
// 把本類對應屬性的值賦給NSMutableURLRequest對應的屬性
[mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
}
}
// 將傳入的parameters添加到mutableRequest中
mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];
return mutableRequest;
}
複製代碼
static NSArray *AFHTTPRequestSerializerObservedKeyPaths()
這個函數其實是將AFHTTPRequestSerializer
類中一些屬性的名字封裝成字符串並以數組形式返回self.mutableObservedChangedKeyPaths
這個屬性在AFURLRequestSerialization
的初始化方法- (instancetype)init
中進行了初始化self.mutableObservedChangedKeyPaths = [NSMutableSet set];
// 觀察AFHTTPRequestSerializerObservedKeyPaths()函數返回的屬性
for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
[self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
}
}
複製代碼
並在KVO方法中進行賦值session
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(__unused id)object
change:(NSDictionary *)change
context:(void *)context
{
if (context == AFHTTPRequestSerializerObserverContext) {
// 若是給當前屬性賦的值不爲null就添加到self.mutableObservedChangedKeyPaths中,不然從其中移除
if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
[self.mutableObservedChangedKeyPaths removeObject:keyPath];
} else {
[self.mutableObservedChangedKeyPaths addObject:keyPath];
}
}
}
複製代碼
由此因此咱們能夠得知self.mutableObservedChangedKeyPaths
中保存的就是咱們設置的AFHTTPRequestSerializer
對象的屬性的集合多線程
[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error]
把parameters
編碼並設置到mutableRequest中- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
// 在debug模式下若是缺乏NSURLRequest對象則會crash
NSParameterAssert(request);
NSMutableURLRequest *mutableRequest = [request mutableCopy];
// 遍歷並對request沒有的屬性進行賦值
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
// 把parameters編碼成字符串
NSString *query = nil;
if (parameters) {
// 若是自定義了參數編碼方式
if (self.queryStringSerialization) {
NSError *serializationError;
// 用戶可經過block自定義參數的編碼方式
query = self.queryStringSerialization(request, parameters, &serializationError);
if (serializationError) {
if (error) {
*error = serializationError;
}
return nil;
}
// 使用默認的參數編碼方式
} else {
switch (self.queryStringSerializationStyle) {
case AFHTTPRequestQueryStringDefaultStyle:
query = AFQueryStringFromParameters(parameters);
break;
}
}
}
// 判斷是不是GET、HEAD、DELETE請求,self.HTTPMethodsEncodingParametersInURI這個屬性在AFURLRequestSerialization的初始化方法- (instancetype)init中進行了初始化
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
if (query && query.length > 0) {
// 將編碼好的參數拼接在url後面
mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
}
// 若是是POST、PUT請求
} else {
// #2864: an empty string is a valid x-www-form-urlencoded payload
if (!query) {
query = @"";
}
if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
[mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
}
// 把編碼好的參數拼到http的body中
[mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
}
return mutableRequest;
}
複製代碼
大概的看一下AFNetworking
默認的的參數編碼方式,AFQueryStringFromParameters()
點進去之後能夠看到是三個方法併發
NSString * AFQueryStringFromParameters(NSDictionary *parameters) {
NSMutableArray *mutablePairs = [NSMutableArray array];
// 遍歷由集合對象處理成AFQueryStringPair元素組成的數組
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
// 把AFQueryStringPair元素的屬性拼接成字符串添加到mutablePairs中,若是有value值就拼接成「field=value」的形式,不然爲「field」
[mutablePairs addObject:[pair URLEncodedStringValue]];
}
// 把mutablePairs中的字符串用&連接成一個字符串
return [mutablePairs componentsJoinedByString:@"&"];
}
NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
return AFQueryStringPairsFromKeyAndValue(nil, dictionary);
}
NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
// 設置排序描述爲按照對象的description屬性升序排列
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];
// 若是value是NSDictionary
if ([value isKindOfClass:[NSDictionary class]]) {
// 將NSDictionary的key按照首字母升序排列後遍歷出nestedKey及其對應的nestedValue,而後遞歸調用AFQueryStringPairsFromKeyAndValue()方法,若是有key值則傳(key[nestedKey], nestedValue),不然傳(nestedKey, nestedValue)
NSDictionary *dictionary = value;
for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
id nestedValue = dictionary[nestedKey];
if (nestedValue) {
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
}
}
// 若是value是NSArray
} else if ([value isKindOfClass:[NSArray class]]) {
// 直接遍歷取出nestedValue,而後遞歸調用AFQueryStringPairsFromKeyAndValue()方法,若是有key值則傳遞(key[], nestedValue),不然傳((null)[], nestedValue)
NSArray *array = value;
for (id nestedValue in array) {
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
}
// 若是value是NSSet
} else if ([value isKindOfClass:[NSSet class]]) {
// 將NSSet的值按照首字母升序排列後遍歷出值obj,而後遞歸調用AFQueryStringPairsFromKeyAndValue()方法,若是有key值則傳(key, obj),不然傳((null), obj)
NSSet *set = value;
for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)];
}
// 若是value不是集合對象
} else {
實例化AFQueryStringPair對象添加到mutableQueryStringComponents數組中,也就是說AFQueryStringPairsFromKeyAndValue()這個方法執行結束後,返回的是由集合對象轉化爲AFQueryStringPair對象的元素組成的數組
[mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
}
return mutableQueryStringComponents;
}
複製代碼
至此,實例化NSMutableURLRequest
對象的任務就結束了,而後就須要再回到- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress success:(void (^)(NSURLSessionDataTask *, id))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
這個方法中,利用上一步實例化好的NSURLSessionDataTask
對象request
生成網絡請求任務NSURLSessionDataTask
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler {
__block NSURLSessionDataTask *dataTask = nil;
url_session_manager_create_task_safely(^{
dataTask = [self.session dataTaskWithRequest:request];
});
[self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];
return dataTask;
}
複製代碼
發現dataTask並非直接建立,而是在一個block中建立,點進url_session_manager_create_task_safely
能夠看到這實際上是作了一個版本的兼容
static void url_session_manager_create_task_safely(dispatch_block_t block) {
if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) {
// Fix of bug
// Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8)
// Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093
// 蘋果在iOS8的時候已經解決了這個bug,這是爲了兼容iOS8以前
dispatch_sync(url_session_manager_creation_queue(), block);
} else {
block();
}
}
複製代碼
這裏做者自定義了一個串行隊列,而且只生成一次
static dispatch_queue_t url_session_manager_creation_queue() {
static dispatch_queue_t af_url_session_manager_creation_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL);
});
return af_url_session_manager_creation_queue;
}
複製代碼
所以,能夠發現若是是在iOS8以前的版本建立dataTask
是在一個同步串行隊列裏,經過查找資料,能夠知道在iOS8以前- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;
這個方法是異步併發執行的,因此會出現實際回調completionHandlers
並非當初task
的回調,而是另外一個task
的回調。
接下來是對生成的dataTask
添加代理
- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
// 這個方法裏面主要生成了一個AFURLSessionManagerTaskDelegate的對象並和NSURLSessionDataTask對象以及AFURLSessionManager對象相關聯
AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
delegate.manager = self;
delegate.completionHandler = completionHandler;
dataTask.taskDescription = self.taskDescriptionForSessionTasks;
[self setDelegate:delegate forTask:dataTask];
delegate.uploadProgressBlock = uploadProgressBlock;
delegate.downloadProgressBlock = downloadProgressBlock;
}
複製代碼
接着點[self setDelegate:delegate forTask:dataTask];
進去
- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
forTask:(NSURLSessionTask *)task
{
// 在debug模式下若是缺乏參數則會crash
NSParameterAssert(task);
NSParameterAssert(delegate);
// 加鎖保證對字典的操做線程安全
[self.lock lock];
// 將NSURLSessionTask對象的taskIdentifier做爲key,將與之對應的AFURLSessionManagerTaskDelegate對象做爲value,存放到字典中
self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
// 爲task添加開始與暫停通知
[self addNotificationObserverForTask:task];
[self.lock unlock];
}
複製代碼
1.在[self addNotificationObserverForTask:task];
方法中添加對task相關通知的接收
- (void)addNotificationObserverForTask:(NSURLSessionTask *)task {
// 接收task開啓和暫停的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task];
}
複製代碼
在通知的響應方法中轉化爲AFNetworking
對外暴漏的通知AFNetworkingTaskDidResumeNotification
和AFNetworkingTaskDidSuspendNotification
- (void)taskDidResume:(NSNotification *)notification {
NSURLSessionTask *task = notification.object;
if ([task respondsToSelector:@selector(taskDescription)]) {
if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task];
});
}
}
}
- (void)taskDidSuspend:(NSNotification *)notification {
NSURLSessionTask *task = notification.object;
if ([task respondsToSelector:@selector(taskDescription)]) {
if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task];
});
}
}
}
複製代碼
爲何不直接發送通知,而是先接收通知而後通過處理後再發送通知呢?這是由於AFNetworking
把NSURLSessionTask
的suspend
和resume
方法利用runtime
的Method Swizzling
交換爲af_suspend
和af_resume
,並在交換後的方法中發送通知以實現對task
開始與暫停的監聽, 可是在一個項目中可能有的網絡請求不是當前session
的,因此要經過task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks
進行判斷這個網絡請求task是否來自當前session
,其中self.taskDescriptionForSessionTasks
其實就是AFURLSessionManager
對象的指針字符串
- (NSString *)taskDescriptionForSessionTasks {
return [NSString stringWithFormat:@"%p", self];
}
複製代碼
到此爲止,對task的處理就結束了。
AFURLSessionManager
遵照了<NSURLSessionDelegate> <NSURLSessionTaskDelegate> <NSURLSessionDataDelegate> <NSURLSessionDownloadDelegate>
四個代理並實現了15個代理方法
AFURLSessionManagerTaskDelegate
只實現了其中6個
1.先看第一個代理
- (void)URLSession:(__unused NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
的實現
- (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
// 由於self.manager屬性關鍵字是weak,因此爲了防止被釋放就用__strong
__strong AFURLSessionManager *manager = self.manager;
// 用來保存請求返回的數據,爲了能夠在block中進行修改,用了__block
__block id responseObject = nil;
// 用來保存發送通知時傳遞的數據,爲了能夠在block中進行修改,用了__block,並進行賦值
__block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
// 使用臨時變量保存請求到的數據,並把保存數據的屬性清空,節約內存
//Performance Improvement from #2672
NSData *data = nil;
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;
}
// 若是設置了下載文件的保存路徑,就傳遞保存路徑,不然若是有請求到的數據,就傳遞請求到的數據
if (self.downloadFileURL) {
userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
} else if (data) {
userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
}
// 若是請求出錯
if (error) {
// 傳遞錯誤信息
userInfo[AFNetworkingTaskDidCompleteErrorKey] = error;
// 用戶能夠自定義調度組和隊列並利用dispatch_group_notify實現對回調完成的監控
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;
responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError];
// 若是有保存下載文件的路徑則返回路徑
if (self.downloadFileURL) {
responseObject = self.downloadFileURL;
}
// 傳遞響應序列化對象
if (responseObject) {
userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
}
// 若是解析出錯則傳遞錯誤對象
if (serializationError) {
userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
}
// 一樣的回調和發送通知
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, serializationError);
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
});
}
}
複製代碼
2.第二個代理- (void)URLSession:(__unused NSURLSession *)session dataTask:(__unused NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
的實現相對簡單
- (void)URLSession:(__unused NSURLSession *)session
dataTask:(__unused NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
// 更新下載進度對象的屬性
self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive;
self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived;
// 保存傳遞的數據
[self.mutableData appendData:data];
}
複製代碼
3.第三個代理- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
是在向服務器傳遞數據時調用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
// 更新上傳進度對象的屬性
self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
self.uploadProgress.completedUnitCount = task.countOfBytesSent;
}
複製代碼
4.第四個代理是在執行下載任務時,按期調用的
- (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;
}
複製代碼
5.第五個代理在重啓下載時調用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
// 更新下載進度對象的屬性
self.downloadProgress.totalUnitCount = expectedTotalBytes;
self.downloadProgress.completedUnitCount = fileOffset;
}
複製代碼
6.第六個代理- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
是下載任務完成後的回調
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
// 若是用戶設置了保存下載文件的路徑,就將下載完的文件從臨時路徑移動過去,移動完成後發送通知
self.downloadFileURL = nil;
if (self.downloadTaskDidFinishDownloading) {
self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
if (self.downloadFileURL) {
NSError *fileManagerError = nil;
if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
}
}
}
}
複製代碼
到此爲止,一個GET請求就結束了,總結一下AFNetworking
作的事情
AFHTTPSessionManager
利用參數method
、URLString
和parameters
生成一個NSMutableURLRequest
對象request
AFURLSessionManager
利用生成的request
生成一個NSURLSessionDataTask
對象dataTask
dataTask
和AFURLSessionManagerTaskDelegate
的對象delegate
利用字典一一對應保存,將delegate
的進度屬性的取消、暫停和開始和dataTask
相對的方法相關聯,並對delegate
和dataTask
的相關屬性添加觀察者對delegate
的上傳下載進度屬性賦值dataTask
的開始於中止添加通知監聽,並向外部發送通知dataTask
的resume
方法進行網絡請求AFURLSessionManagerTaskDelegate
的對象delegate
實現的六個代理方法監聽進度以及處理請求返回的數據,若是須要解析數據會在異步併發隊列中進行,而後在最開始生成的最大併發數爲1的NSOperationQueue
的對象operationQueue
串行回調結果。源碼閱讀系列:AFNetworking
源碼閱讀:AFNetworking(二)——AFURLRequestSerialization
源碼閱讀:AFNetworking(三)——AFURLResponseSerialization
源碼閱讀:AFNetworking(四)——AFSecurityPolicy
源碼閱讀:AFNetworking(五)——AFNetworkReachabilityManager
源碼閱讀:AFNetworking(六)——AFURLSessionManager
源碼閱讀:AFNetworking(七)——AFHTTPSessionManager
源碼閱讀:AFNetworking(八)——AFAutoPurgingImageCache
源碼閱讀:AFNetworking(九)——AFImageDownloader
源碼閱讀:AFNetworking(十)——AFNetworkActivityIndicatorManager
源碼閱讀:AFNetworking(十一)——UIActivityIndicatorView+AFNetworking
源碼閱讀:AFNetworking(十二)——UIButton+AFNetworking
源碼閱讀:AFNetworking(十三)——UIImageView+AFNetworking
源碼閱讀:AFNetworking(十四)——UIProgressView+AFNetworking