直播中的多定时器计时

引言:

直播过程中,观众用户可以对主播进行送礼,送礼往往支持礼物的连送。但是每个礼物的连送计时是相互独立的,这里需要用到多个定时器同时进行连送计时。本文使用了GCD定时器来实现,旨在提供一种实现思路,欢迎讨论

实现效果:

picture.gif

功能说明:

  • 选中礼物后可以点击【赠送】,点击【赠送】后调用礼物赠送接口并修改按钮文案进行倒计时
  • 倒计时时长由后台返回礼物连击时长字段控制,倒计时单位为100ms
  • 再次点击同一礼物的赠送按钮倒计时重新计算
  • 各个礼物的连送倒计时相互独立,切换礼物,按钮倒计时同时切换

如何实现


// 点击赠送调用该方法进行计时,同时传入礼物对应Model
- (void)startCoutingWithGiftModel:(RYIMGiftModel *)giftModel {
    
    // 获取礼物ID
    NSString *giftId = giftModel.giftId;
    
    // 以礼物ID为Key获取定时器字典中对应的定时器
    __block dispatch_source_t timer = self.timerDict[giftId];
    
    // 获取全局并发队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    // 创建定时器
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    // 设置时间精度,设置为100ms
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 100.0 * NSEC_PER_MSEC, 0);
    
    // 获取礼物Model中连击时段并设置为倒计时时长
    NSTimeInterval timeInterval = giftModel.continuityTime;
    NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:timeInterval];
    
    // 设置倒计时回调,回调方法的执行频率为100ms/次
    dispatch_source_set_event_handler(timer, ^{
        NSString *timeStr;
        
        // 当前时间与设定结束时间的时间间隔,interval单位为s,应产品要求倒计时以毫秒展示,故乘以10
        int interval = [endTime timeIntervalSinceNow] * 10;
        
        // 按倒计时时长确定文案
        if (interval > 0) {
            timeStr = [NSString stringWithFormat:@"连击 %d", interval];
        } else {
            timeStr = @"赠送";
            dispatch_source_cancel(timer);
        }
        
        // 选中礼物时(无选中礼物时 selectedIndex == -1)
        if (self.selectedIndex != -1) {
        
            // 根据礼物ID获取对应定时器
            RYIMGiftModel *currentGiftModel = self.gifts[self.selectedIndex];
            NSString *currentGiftId = currentGiftModel.giftId;
            dispatch_source_t currentTimer = self.timerDict[currentGiftId];
            
            // 当前回调定时器与选中礼物对应定时器为同一个
            if (currentTimer == timer) {
            
                // 回到主线程修改按钮文案
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.handselLab.text = timeStr;
                });
            }
        }
    });
    
    // 将定时器装入字典
    [self.timerDict setObject:timer forKey:giftId];
    
    // 重置定时器(每次点击赠送重新计时)
    dispatch_resume(timer);
}

你可能感兴趣的:(直播中的多定时器计时)