GCD信号量多组操作
近期在进行产品迭代时遇到了一个问题,就是在一个列表中进行两次请求,但是只有在两个网络请求全部结束后才停止列表刷新。这个需求我们经常遇到。我们可以用线程组或者信号量来处理。我代码中用的是信号量。
但是因为这次的代码使用swift写的,途中遇到了很多问题。毕竟oc和swift写法还是有很大不同。在这里,我把代码附上。
OC版:
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); dispatch_queue_t queue = dispatch_get_global_queue(0, 0); // 轮播图 [SMDataRequest requestBigHomeScrollImageSuccess:^(SMFirstLayerData *response) { self.scrollImages = response.data; SMLog(@"轮播图 ++++%@", [NSThread currentThread]); dispatch_semaphore_signal(semaphore); } Failure:^(NSError *error) { dispatch_semaphore_signal(semaphore); }]; // 猜你喜欢 [SMDataRequest requestFavoriteProductWithUserId:USER_ID currentPage:1 Success:^(NSDictionary *response) { dispatch_semaphore_signal(semaphore); SMLog(@"猜你喜欢 ++++%@", [NSThread currentThread]); // 数据处理 } Failure:^(NSError *error) { dispatch_semaphore_signal(semaphore); }]; dispatch_async(queue, ^{ dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); SMLog(@"全部加载好了 ++++%@", [NSThread currentThread]); [self.bigHomeCollectionView.mj_header endRefreshing]; });
swift版:
let semaphore = DispatchSemaphore.init(value: 0) let queue = DispatchQueue.global() GetActivityFriendAllApi(Uid: UserModel.shareInstance.uid ?? 0, Status: 1, PageOn: 1,ApiType:1,pageSize : 100).startWithCompletionBlock(success: { (request:YTKBaseRequest!) in print("===succ===="+"1"+"======") semaphore.signal() }) { (request:YTKBaseRequest!) in print("===error===="+"1"+"======") semaphore.signal() } GetActivityFriendAllApi(Uid: UserModel.shareInstance.uid ?? 0, Status: 1, PageOn: 1,ApiType:1,pageSize : 100).startWithCompletionBlock(success: { (request:YTKBaseRequest!) in print("===succ===="+"2"+"======") semaphore.signal() }) { (request:YTKBaseRequest!) in print("===error===="+"2"+"======") semaphore.signal() } queue.async { // semaphore.wait(timeout: DispatchTime.distantFuture) // semaphore.wait(timeout: DispatchTime.distantFuture) semaphore.wait() semaphore.wait() print("======="+"123"+"======") }