iOS开发,如何在多个接口请求到数据之后,再刷新UI界面

1、使用 DispatchGroup解决,如下图,我在自己项目中使用真实的网络请求接口实现( 这种是不开启子线程的线程组)

 

 1     func test() {
 2         let group = DispatchGroup()
 3         group.enter()
 4         productListParaDict["storeId"] = getCurrentStoreId()
 5         NetWorkRequest(.storeProductList(parameters: productListParaDict), completion: { (responseString) -> (Void) in
 6             print("商品列表数据已成功获取")
 7             group.leave()
 8         }) { (responseString) -> (Void) in
 9             print("商品列表数据获取失败")
10             group.leave()
11         }
12         print("开始请求商品数量")
13         group.enter()
14         var param : [String:Any] = Dictionary()
15         param["storeId"] = getCurrentStoreId()
16         param["enable"] = "1"
17         NetWorkRequest(.storeProductGetStateCount(parameters: param), completion: { (responseString) -> (Void) in
18             print("商品数量数据已成功获取")
19             group.leave()
20         }) { (responseString) -> (Void) in
21             print("商品数量数据获取失败")
22             group.leave()
23         }
24         group.notify(queue: DispatchQueue.main) {
25             print("更新UI")
26         }
27     }

来看下控制台的打印输出,是不是实现了,两个接口数据都拿到了,然后到主线程去刷新UI界面了

 

 

2、开启子线程的线程组

 1     func test1() {
 2         let queneE = DispatchQueue(label: "group.quene")
 3         let groupE = DispatchGroup()
 4         queneE.async(group: groupE, qos: .default, flags: []) {
 5             groupE.enter()
 6             self.productListParaDict["storeId"] = getCurrentStoreId()
 7             NetWorkRequest(.storeProductList(parameters: self.productListParaDict), completion: { (responseString) -> (Void) in
 8                 print("商品列表数据已成功获取")
 9                 groupE.leave()
10             }) { (responseString) -> (Void) in
11                 print("商品列表数据获取失败")
12                 groupE.leave()
13             }
14         }
15         print("开始请求商品数量")
16         queneE.async(group: groupE, qos: .default, flags: []) {
17             groupE.enter()
18             var param : [String:Any] = Dictionary()
19             param["storeId"] = getCurrentStoreId()
20             param["enable"] = "1"
21             NetWorkRequest(.storeProductGetStateCount(parameters: param), completion: { (responseString) -> (Void) in
22                 print("商品数量数据已成功获取")
23                 groupE.leave()
24             }) { (responseString) -> (Void) in
25                 print("商品数量数据获取失败")
26                 groupE.leave()
27             }
28         }
29         groupE.notify(queue: DispatchQueue.main) {
30             print("更新UI")
31         }
32     }

同样的,来看下控制台的打印输出

 

posted @ 2020-06-11 17:31  晨光微  阅读(1784)  评论(0编辑  收藏  举报