关于objective-c:iOS处理多个网络请求的先后依赖关系

在iOS开发中咱们常常会遇到多网络申请的问题,有时候须要在一个网络申请完结之后再去申请另一个网络,其实最简略也是最low的办法就是在一个网络申请胜利的回调中再去申请另外一个接口信息

应用信号量计数器来实现的代码如下:

static NSString *userSign;
static NSString *userId;

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

dispatch_group_async(group, queue, ^{
    [[BFLoginService shareInstance] getImSignWith: @"gjs598"  complete:^(id  _Nonnull data, RequestError * _Nonnull error) {
        // 工作1
        NSLog(@"获取im签名实现%@", data[@"UserSig"]);
        userSign = data[@"UserSig"];
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
});

dispatch_group_async(group, queue, ^{
    [[BFLoginService shareInstance] getImUserId:^(id  _Nonnull data, RequestError * _Nonnull error) {
        // 工作2
        NSLog(@"获取用户Id实现%@", data[@"userId"]);
        userId = data[@"userId"];
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
});

dispatch_group_notify(group, queue, ^{
    NSLog(@"啊啊啊啊啊啊%@ ----- %@", userId, userSign);
    // 工作1/工作2都实现了, 当初执行工作3
    [[V2TIMManager sharedInstance] login: userId userSig: userSign succ:^{
        // NSLog(@"id登陆胜利");
        
        // @weakify(self)
         [[V2TIMManager sharedInstance] getConversationList: INT_MAX count: INT_MAX succ: ^(NSArray<V2TIMConversation *> *list, uint64_t lastTS, BOOL isFinished) {
             // @strongify(self)
             // [self updateConversation: list];
             NSLog(@"会话列表%@", list);
         } fail:^(int code, NSString *msg) {
             NSLog(@"拉取会话列表失败");
         }];
        
    } fail:^(int code, NSString *desc) {
        NSLog(@"id登陆失败了----------");
        NSLog(@"%@", desc);
    }];
});

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理