IOS 如何處理多個網絡請求的先后(依賴)關系


函數介紹

一。dispatch_semaphore_create(M)

創建一個值為M的信號量

dispatch_semaphore_wait(信號量,等待時間)

如果該信號量的值大於0,則使其信號量的值-1,否則,阻塞線程直到該信號量的值大於0或者達到等待時間。

dispatch_semaphore_signal(信號量)

釋放信號量,使得該信號量的值加1

dispatch_group_t group = dispatch_group_create();
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_queue_t queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
    for (int j = 0; j < 4; j ++) {
        dispatch_group_async(group, queue, ^{

         if (j == 0) {
                [self loadOne:semaphore];
            }else if (j == 1){
                [self loadTwe:semaphore];
            }else if (j == 2){
                [self loadThree:semaphore];
            }else{
                [self loadFour:semaphore];
            }
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        });
    }
    
    dispatch_group_notify(group, queue, ^{
        //所有請求返回數據后執行
        NSLog(@"完成");
    });

- (void)loadOne:(dispatch_semaphore_t)group
{

      //完成

      dispatch_semaphore_signal(group);

}

 

二。使用GCD的dispatch_group_t

創建一個dispatch_group_t

每次網絡請求前先dispatch_group_enter,請求回調后再dispatch_group_leave,enter和leave必須配合使用,有幾次enter就要有幾次leave,否則group會一直存在。

當所有enter的block都leave后,會執行dispatch_group_notify的block。

dispatch_group_t downloadGroup = dispatch_group_create();
    NSString *requestURL11 =  [NSString stringWithFormat:@"%@api/index/index?",MYURL];
    dispatch_group_enter(downloadGroup);
    [[HttpRequest sharedInstance] postWithURLString:requestURL11 headStr:nil parameters:nil success:^(id responseObject) {
        NSLog(@"success11");
        dispatch_group_leave(downloadGroup);
    } failure:^(id failure) {
        NSLog(@"failure111");
    }];
    
    
    NSString *requestURL22 =  [NSString stringWithFormat:@"%@api/recommend/index?",MYURL];
    dispatch_group_enter(downloadGroup);
    [[HttpRequest sharedInstance] postWithURLString:requestURL22 headStr:nil parameters:nil success:^(id responseObject) {
        NSLog(@"success22");
        dispatch_group_leave(downloadGroup);
    } failure:^(id failure) {
        NSLog(@"failure22");
    }];

    dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{
        NSLog(@"end");
    });

 

三。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM