36

多个请求统一更新界面

 5 years ago
source link: http://www.cocoachina.com/ios/20180705/24064.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

7rUbey6.jpg!web

一个列表页面

10个请求接口

依据数据展现界面

1. 问题

碰到一个主页的需求,涉及到(1)自动播放的图片接口 (2)业务栏内容的接口 (3)热点广告的接口 (4)热卖商品的接口 (5)附件商店的接口 (6)附近商品的接口 (7)推荐商品的接口 (8)。。。

前前后后打开主页涉及到10几个接口,因为主页使用的是一个tableview来展现,所以会涉及到刷新tableview的问题。如果按一个接口调用后再调用下一个接口的方式,那么存在效率差的问题。

2. 解决方案

使用dispatch_group_t的方法将不同接口使用异步进行获取,等到所有的接口返回数据后,再统一更新界面。

这样可以充分的发挥多线程的优势,提高访问速度和用户的体验。

3. 代码实现

@property (nonatomic, strong) dispatch_group_t myGroup;
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_group_t group = dispatch_group_create();
    self.myGroup = group;
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        [self fetchWorkStatus];
        DLog(@"111");
    });
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        [self fetchPermission];
        DLog(@"222");
    });
    dispatch_group_notify(group, queue, ^{
        DLog(@"333");
    });
    DLog(@"666");
}

其中的fetchWorkStatus 和 fetchPermission是网络请求的方法。

- (void)fetchWorkStatus
{
    [self.mainViewModel queryHome:^(ErrorCode status, NSString *message, NSDictionary *data) {
        DLog(@"444");
        dispatch_group_leave(self.myGroup);
    }];
}
- (void)fetchPermission
{
    [self.mainViewModel fetchUserPermissionWithUid:[HXQUserAccount currentAccount].userInfoModel.uidStr
                                         completed:^(ErrorCode status, NSString *message, NSArray
<nsnumber nbsp="">
  *permissionArr) {
                                             DLog(@"555");
                                             dispatch_group_leave(self.myGroup);
                                         }];
}
</nsnumber>

重点:在请求返回后调用dispatch_group_leave方法。

打印日志为:

实现多线程并发请求数据,并在所有请求完成后,再执行一个操作。即在333中执行界面刷新。

作者:蝴蝶之梦天使

链接:https://www.jianshu.com/p/c6c2eb02298a


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK