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 }
同樣的,來看下控制台的打印輸出