iOS多個(gè)網(wǎng)絡(luò)請(qǐng)求同步執(zhí)行

這里所說的同步執(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ù)完成
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末呕屎,一起剝皮案震驚了整個(gè)濱河市让簿,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌秀睛,老刑警劉巖尔当,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異蹂安,居然都是意外死亡椭迎,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門田盈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來畜号,“玉大人,你說我怎么就攤上這事允瞧〖蛉恚” “怎么了蛮拔?”我有些...
    開封第一講書人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)痹升。 經(jīng)常有香客問我建炫,道長(zhǎng),這世上最難降的妖魔是什么疼蛾? 我笑而不...
    開封第一講書人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任踱卵,我火速辦了婚禮,結(jié)果婚禮上据过,老公的妹妹穿的比我還像新娘惋砂。我一直安慰自己,他們只是感情好绳锅,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開白布西饵。 她就那樣靜靜地躺著,像睡著了一般鳞芙。 火紅的嫁衣襯著肌膚如雪眷柔。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,365評(píng)論 1 302
  • 那天原朝,我揣著相機(jī)與錄音驯嘱,去河邊找鬼。 笑死喳坠,一個(gè)胖子當(dāng)著我的面吹牛鞠评,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播壕鹉,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼剃幌,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了晾浴?” 一聲冷哼從身側(cè)響起负乡,我...
    開封第一講書人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎脊凰,沒想到半個(gè)月后抖棘,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡狸涌,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年切省,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片杈抢。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡数尿,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出惶楼,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布歼捐,位于F島的核電站何陆,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏豹储。R本人自食惡果不足惜贷盲,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望剥扣。 院中可真熱鬧巩剖,春花似錦、人聲如沸钠怯。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽晦炊。三九已至鞠鲜,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間断国,已是汗流浹背贤姆。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留稳衬,地道東北人霞捡。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像薄疚,于是被迫代替她去往敵國(guó)和親弄砍。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354