赞
踩
Swift4.0 中,GCD的API更加独立,而不再是像OC一样了,所以我们经常遇到这样一种场景,某个页面需要多个网络请求才可以获得全部数据,在没有顺序要求的情况下,使用GCD Group进行线程调度是最合适的,如果存在顺序要求,需要使用信号量,信号量的具体方法在这里不讨论,下面展示如何使用Group请求多个线程网络数据:
- func get(){
-
- let queue = DispatchQueue.init(label: "getCount")//定义队列
- let group = DispatchGroup()//创建一个组
-
- //将队列放进组里
- queue.async(group: group, execute: {
- group.enter()//开始线程1
-
- let url = rootUrl + "/getDetailedQuestion.do"
- let parame:[String:AnyObject] = {
- return ["questionId":self.id]
- }() as [String : AnyObject]
-
- AlaRequestManager.shared.POST(urlString: url, params: parame, success: ({success in
- // print(success)
- print("thread1")
- group.leave()//线程1结束
- }))
-
- })
-
-
- queue.async(group: group, execute: {
- group.enter()//开始线程2
-
- let url = rootUrl + "/getDetailedQuestion.do"
- let parame:[String:AnyObject] = {
- return ["questionId":self.id]
- }() as [String : AnyObject]
-
- AlaRequestManager.shared.POST(urlString: url, params: parame, success: ({success in
- // print(success)
- print("thread2")
- group.leave()//线程2结束
- }))
- })
-
-
- group.notify(queue: queue){
- //队列中线程全部结束
- print("end")
- }
-
-
- }
-
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。