這里所說的同步執(zhí)行是指多個(gè)網(wǎng)絡(luò)請(qǐng)求按順序執(zhí)行圣絮,但這些請(qǐng)求還是可以在異步線程處理的不會(huì)阻塞主線程蚤认;首先我們看一個(gè)實(shí)際的應(yīng)用場(chǎng)景:
登錄時(shí)發(fā)起請(qǐng)求A稳摄,請(qǐng)求成功后得到返回的用戶信息室囊;根據(jù)得到的信息作為參數(shù)再發(fā)送網(wǎng)絡(luò)請(qǐng)求B藻雪;這里就要求網(wǎng)絡(luò)請(qǐng)求B必須是在網(wǎng)絡(luò)請(qǐng)求A回調(diào)后再調(diào)用:A--->B秘噪;
類似的需求,在實(shí)際開發(fā)中或多或少會(huì)碰到勉耀;現(xiàn)在我們就來處理這種需求
NSURLConnection
NSURLConnection封裝了類似的同步請(qǐng)求功能:
@interface NSURLConnection (NSURLConnectionSynchronousLoading)
/*!
@discussion
A synchronous load for the given request is built on
top of the asynchronous loading code made available
by the class. The calling thread is blocked while
the asynchronous loading system performs the URL load
on a thread spawned specifically for this load
request. No special threading or run loop
configuration is necessary in the calling thread in
order to perform a synchronous load. For instance,
the calling thread need not be running its run loop.
….
*/
+ (nullable NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse * _Nullable * _Nullable)response error:(NSError **)error API_DEPRECATED("Use [NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSession.h", macos(10.3,10.11), ios(2.0,9.0), tvos(9.0,9.0)) API_UNAVAILABLE(watchos);
@end
以上A指煎、B請(qǐng)求同步執(zhí)行的簡(jiǎn)單示例:
NSURLRequest *rqs = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://github.com"]];
NSData *githubData = [NSURLConnection sendSynchronousRequest:rqs returningResponse:nil error:nil];
NSLog(@"A業(yè)務(wù),%@",githubData);
rqs = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.reibang.com"]];
NSData *jianshuData = [NSURLConnection sendSynchronousRequest:rqs returningResponse:nil error:nil];
NSLog(@"B業(yè)務(wù),%@",jianshuData);
NSURLSession
使用NSURLConnection很方便的實(shí)現(xiàn)了同步請(qǐng)求,但這套API老早就已經(jīng)DEPRECATED
便斥,需要使用NSURLSession代替至壤;
但是NSURLSession并沒有提供類似sendSynchronousRequest的接口;那么枢纠,使用NSURLSession實(shí)現(xiàn)同步請(qǐng)求的一個(gè)簡(jiǎn)單方式就是在A請(qǐng)求成功回調(diào)里再調(diào)用B請(qǐng)求像街;類似代碼如下:
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:@"https://github.com"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"A業(yè)務(wù),%@",data);
[[session dataTaskWithURL:[NSURL URLWithString:@"http://www.reibang.com"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"B業(yè)務(wù),%@",data);
}] resume];
}] resume];
如果我們的業(yè)務(wù)不只是A、B同步,而是A--->B--->C---D宅广,那就需嵌套更多層葫掉,形成了Callback Hell
;這樣的代碼是很丑陋的跟狱,可讀性俭厚、維護(hù)性都比較差;
接下來驶臊,我們就自己動(dòng)手來實(shí)現(xiàn)類似NSURLConnection的同步請(qǐng)求的方法挪挤;
iOS同步方案有很多種,我之前的文章都有詳細(xì)介紹:
細(xì)數(shù)iOS中的線程同步方案(一)
細(xì)數(shù)iOS中的線程同步方案(二)
這里我們選用性能較高的GCD信號(hào)量semaphore关翎;
@implementation NSURLSession (Sync)
+ (nullable NSData *)sendSynchronousURL:(NSURL *)url returningResponse:(NSURLResponse * _Nullable __strong * _Nullable)response error:(NSError * __strong *)error {
__block NSData *data;
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable tData, NSURLResponse * _Nullable tResponse, NSError * _Nullable tError) {
// 子線程
*response = tResponse;
*error = tError;
data = tData;
dispatch_semaphore_signal(sem);
}]resume];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
return data;
}
@end
這里給NSURLSession添加了分類扛门,封裝了和NSURLConnection中同步請(qǐng)求一樣的方法;需要注意的是纵寝,方法參數(shù)中response和error前都加了__strong
內(nèi)存修飾符论寨,這是因?yàn)槿绻麤]有明確指定內(nèi)存的修飾符(strong, weak, autoreleasing),類似NSURLResponse **reponse爽茴,NSError **error的臨時(shí)變量葬凳,在ARC下編譯器會(huì)默認(rèn)添加__autoreleasing內(nèi)存修飾符,而在block中捕獲一個(gè)__autoreleasing的out-parameter很容易造成內(nèi)存問題室奏;Xcode會(huì)提示警告信息Block captures an autoreleasing out-parameter, which may result in use-after-free bugs
這篇博客詳細(xì)解釋了原因:https://www.cnblogs.com/tiantianbobo/p/11653843.html
封裝好之后火焰,A、B同步請(qǐng)求的代碼就可以這樣寫了:
NSData *githubData = [NSURLSession sendSynchronousURL:[NSURL URLWithString:@"https://github.com"] returningResponse:nil error:nil];
NSLog(@"A業(yè)務(wù),%@",githubData);
NSData *jianshuData = [NSURLSession sendSynchronousURL:[NSURL URLWithString:@"http://www.reibang.com"] returningResponse:nil error:nil];
NSLog(@"B業(yè)務(wù),%@",jianshuData);
AFNetworking
實(shí)際開發(fā)中胧沫,大部分人應(yīng)該都是使用AFNetworking處理網(wǎng)絡(luò)請(qǐng)求的昌简;AFNetworking3.x其實(shí)也是對(duì)NSURLSession的封裝;
AFNetworking中貌似也沒有提供類似sendSynchronousURL同步請(qǐng)求的方法绒怨;按照之前NSURLSession的思路纯赎,現(xiàn)在同樣使用GCD信號(hào)量實(shí)現(xiàn)AFNetworking的同步請(qǐng)求:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[manager GET:@"https://github.com" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"A業(yè)務(wù),%@",responseObject);
dispatch_semaphore_signal(sem);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@", error.localizedDescription);
dispatch_semaphore_signal(sem);
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
[manager GET:@"http://www.reibang.com" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"B業(yè)務(wù),%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@", error.localizedDescription);
}];
如果你在主線程運(yùn)行以上代碼,會(huì)發(fā)現(xiàn)什么都不會(huì)輸出窖逗;這是因?yàn)锳FNetworking回調(diào)默認(rèn)是主線程址否,這樣dispatch_semaphore_wait和dispatch_semaphore_signal在同一個(gè)線程餐蔬,這樣就死鎖了碎紊;所以以上代碼需要放在異步線程執(zhí)行,類似:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
......
});
AFNetworking和線程有關(guān)的屬性
在AFURLSessionManager.h中樊诺,可以看到以下3個(gè)和線程有關(guān)的屬性
/**
The operation queue on which delegate callbacks are run.
*/
@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
/**
The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
*/
@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
/**
The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
*/
@property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
- operationQueue
NSURLSession回調(diào)的隊(duì)列仗考,創(chuàng)建session時(shí)使用;AFN源碼:
self.operationQueue = [[NSOperationQueue alloc] init];
self.operationQueue.maxConcurrentOperationCount = 1;
self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];
NSURLSession的delegateQueue設(shè)置為[NSOperationQueue mainQueue]則session回調(diào)就是主線程词爬,[[NSOperationQueue alloc] init]則會(huì)是子線程
[[session dataTaskWithURL:[NSURL URLWithString:@"https://github.com"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 主線程 or 子線程
}]resume];
([NSURLSession sharedSession]創(chuàng)建的session的delegateQueue為主隊(duì)列)
- completionQueue
AFN回調(diào)的隊(duì)列秃嗜,默認(rèn)主隊(duì)列;前面GCD信號(hào)量同步執(zhí)行的方法,可以指定completionQueue為異步隊(duì)列則可以在主線程調(diào)用:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// 指定回調(diào)隊(duì)列
manager.completionQueue = dispatch_queue_create("sync_request", DISPATCH_QUEUE_SERIAL);
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[manager GET:@"https://github.com" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"A業(yè)務(wù),%@",responseObject);
dispatch_semaphore_signal(sem);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@", error.localizedDescription);
dispatch_semaphore_signal(sem);
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
[manager GET:@"http://www.reibang.com" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"B業(yè)務(wù),%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@", error.localizedDescription);
}];
- completionGroup
直接看源碼:
- (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)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, serializationError);
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
...
}
NSURLSession請(qǐng)求回調(diào)里锅锨,使用了GCD group處理AFN自己的回調(diào)叽赊;使用group的意圖,應(yīng)該是為了處理批量網(wǎng)絡(luò)請(qǐng)求宜狐;提供的completionGroup就是供開發(fā)者方便調(diào)用dispatch_group_wait或dispatch_group_notify實(shí)現(xiàn)所有請(qǐng)求完成后之后的操作蛀缝;
如C請(qǐng)求需要使用A冯乘、B返回的數(shù)據(jù)作為參數(shù)請(qǐng)求,那么C需要等A塔橡、B都完成后才執(zhí)行,且A霜第、B都是異步葛家;即 A & B ---> C;
代碼實(shí)現(xiàn):
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
dispatch_group_t group = dispatch_group_create();
manager.completionGroup = group;
[manager GET:..]; // A請(qǐng)求
[manager GET:...]; // B請(qǐng)求
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"AB業(yè)務(wù)完成");
});
但是泌类,實(shí)際運(yùn)行結(jié)果并不正確癞谒;@"AB業(yè)務(wù)完成"會(huì)立即執(zhí)行;這是因?yàn)閐ispatch_group_async是在NSURLSession代理回調(diào)中調(diào)用的刃榨,即需要等到異步請(qǐng)求有結(jié)果時(shí)才調(diào)用扯俱,因此在調(diào)用dispatch_group_notify時(shí),group內(nèi)并沒有任務(wù)所有無需等待喇澡;
這樣的問題github上有類似的issue:https://github.com/AFNetworking/AFNetworking/issues/1926
對(duì)于completionGroup暫時(shí)還沒理解它的用途是什么迅栅;
如果想要實(shí)現(xiàn)以上功能,可以自己開個(gè)group晴玖,通過dispatch_group_enter读存、dispatch_group_leave來控制同步;
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
dispatch_group_t group = dispatch_group_create();
[manager GET:@"https://github.com" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"A業(yè)務(wù),%@",responseObject);
dispatch_group_leave(group);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@", error.localizedDescription);
dispatch_group_leave(group);
}];
dispatch_group_enter(group);
[manager GET:@"http://www.reibang.com" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"B業(yè)務(wù),%@",responseObject);
dispatch_group_leave(group);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@", error.localizedDescription);
dispatch_group_leave(group);
}];
dispatch_group_enter(group);
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"AB業(yè)務(wù)完成");
});
輸出結(jié)果:
B任務(wù),{length = 39986, bytes = 0x3c21444f 43545950 45206874 6d6c3e0a ... 3c2f6874 6d6c3e0a }
A任務(wù),{length = 120516, bytes = 0x0a0a0a0a 0a0a3c21 444f4354 59504520 ... 2f68746d 6c3e0a0a }
AB業(yè)務(wù)完成