YH_BarrageTableView.m 14.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
//
//  YH_BarrageTableView.m
//  YHBarrage
//
//  Created by Arthur on 16/6/6.
//  Copyright © 2016年 YOHO!. All rights reserved.
//

#import "YH_BarrageTableView.h"
#import "NSMutableArray+QueueAdditions.h"
#import "YH_BarrageMsgCell.h"
#import "YH_BarrageJoinCell.h"
#import "UtilsMacros.h"
#import <pthread.h>
#define kMessageCellID @"MessageCelliden"
#define kJoinCellID @"JoinCellIden"
#define MaxMessageCacheCapacity 20
#define kCacheProcessingTimerInterval 2

#define IsStrEmpty(_ref)            (IsNilOrNull(_ref) || (![(_ref) isKindOfClass:[NSString class]]) || ([(_ref) isEqualToString:@""]))

@interface YH_BarrageTableView (){
    NSTimer *_cacheProcessingTimer; // 定时将缓冲区数据加到dataMutableArray
    NSTimer *_scrollingTableViewTimer; // 定时刷新tableview
    dispatch_queue_t _syncQueue;
    NSMutableArray *_messageBuffer; // 缓冲消息
    
}

@property (strong, nonatomic) NSMutableArray *dataMutableArray;
@property (nonatomic) BOOL manualScrolling; //是否手动滑动列表
@property (nonatomic) BOOL isMutipleJoin; // 连续两条数据都是【用户加入】的消息
@property (nonatomic) NSUInteger newMsgCount; // 新消息数量
@property (strong, nonatomic) dispatch_queue_t messageProgressingQueue;
//@property (nonatomic) NSUInteger lastRow;     // 当手动滑动tableview时,记录最后一条cell的位置


@end

@implementation YH_BarrageTableView
{
    NSMutableArray *_dataMutableArray;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.delegate = self;
        self.dataSource = self;
        _syncQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _messageBuffer = [[NSMutableArray alloc]init];
        self.dataMutableArray = [[NSMutableArray alloc]init];
        
        // 缓冲区定时器
        if (_cacheProcessingTimer == nil) {
            _cacheProcessingTimer = [NSTimer timerWithTimeInterval:kCacheProcessingTimerInterval target:self selector:@selector(appendCacheToDataArray) userInfo:nil repeats:YES];
            [[NSRunLoop mainRunLoop] addTimer:_cacheProcessingTimer forMode:NSRunLoopCommonModes];
        }
    }
    
    [self setBackgroundColor:[UIColor clearColor]];
    [self setShowsVerticalScrollIndicator:NO];
    self.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    return self;
}

-(id)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    id hitView = [super hitTest:point withEvent:event];
    if (hitView == self) return nil;
    else return hitView;
}

- (void)reset
{
    if (_cacheProcessingTimer) {
        [_cacheProcessingTimer invalidate];
        _cacheProcessingTimer = nil;
    }
    
    if (_scrollingTableViewTimer) {
        [_scrollingTableViewTimer invalidate];
        _scrollingTableViewTimer = nil;
    }
}
- (void)resetDataMutableArray
{
    [self.dataMutableArray removeAllObjects];
}

- (void)yhBarrageTableView:(YH_BarrageTableView *)barrageTableView insertCellWithItem:(NSDictionary *)itemDic
{
    
    __weak typeof (self) weakSelf = self;
    __strong typeof (weakSelf) strongSelf = weakSelf;
    
    if (itemDic && ![itemDic isEqual:[NSNull null]] && !IsStrEmpty([itemDic objectForKey:@"name"])) {
        if (0) {
//            [self greenChannel:itemDic];
        } else {
            
            if ([[itemDic objectForKey:@"cmd"] longValue] == 4 && !self.manualScrolling) {
                // 如果是用户加入的消息,则不加入到缓冲区
                [self newUserJoin:itemDic];
            } else {
                // 现将数据插入到cache
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    YH_BarrageMsgModel *message = [[YH_BarrageMsgModel alloc]initWithDictionary:itemDic error:nil];
                    
                    [strongSelf->_messageBuffer enqueue:message];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (weakSelf.manualScrolling) {
                            weakSelf.newMsgCount ++ ;
                            if ([weakSelf.barrageScrollingDelegate respondsToSelector:@selector(manualScrollingWithNewMsgCount:)]) {
                                [weakSelf.barrageScrollingDelegate manualScrollingWithNewMsgCount:[NSString stringWithFormat:@"%ld", weakSelf.newMsgCount]];
                            }
                        } else {
                            weakSelf.newMsgCount = 0;
                            if ([weakSelf.barrageScrollingDelegate respondsToSelector:@selector(autoScollingCallback)]) {
                                [weakSelf.barrageScrollingDelegate autoScollingCallback];
                                CGPoint bottomOffset = CGPointMake(0, weakSelf.contentSize.height - weakSelf.bounds.size.height);
                                [weakSelf setContentOffset:bottomOffset animated:YES];
                            }
                        }
                    });
                    
                });
                
            }
            
        }
        
    }
    
    
    
}

- (void)newUserJoin:(NSDictionary *)item {
    __weak typeof (self) weakSelf = self;
    if (pthread_main_np() != 0) {
        // main thread
        [weakSelf caculateContentInset];
        YH_BarrageMsgModel *newMessage = [[YH_BarrageMsgModel alloc]initWithDictionary:item error:nil];
        YH_BarrageMsgModel *oldMessage = [weakSelf.dataMutableArray lastObject];
        
        if ([weakSelf.dataMutableArray count] && oldMessage && oldMessage.cmd == newMessage.cmd && oldMessage.cmd == 4) {
            [weakSelf.dataMutableArray replaceObjectAtIndex:[weakSelf.dataMutableArray count]-1 withObject:newMessage];
        } else {
            [weakSelf.dataMutableArray addObject:newMessage];
        }
        
        [weakSelf reloadData];
        CGPoint bottomOffset = CGPointMake(0, weakSelf.contentSize.height - weakSelf.bounds.size.height);
        [weakSelf setContentOffset:bottomOffset animated:YES];
    }else {
        dispatch_sync(dispatch_get_main_queue(), ^{
            [weakSelf caculateContentInset];
            YH_BarrageMsgModel *newMessage = [[YH_BarrageMsgModel alloc]initWithDictionary:item error:nil];
            YH_BarrageMsgModel *oldMessage = [weakSelf.dataMutableArray lastObject];
            
            if ([weakSelf.dataMutableArray count] && oldMessage && oldMessage.cmd == newMessage.cmd && oldMessage.cmd == 4) {
                [weakSelf.dataMutableArray replaceObjectAtIndex:[weakSelf.dataMutableArray count]-1 withObject:newMessage];
            } else {
                [weakSelf.dataMutableArray addObject:newMessage];
            }
            
            [weakSelf reloadData];
            CGPoint bottomOffset = CGPointMake(0, weakSelf.contentSize.height - weakSelf.bounds.size.height);
            [weakSelf setContentOffset:bottomOffset animated:YES];
        });
    }
    
}
// 将缓冲区中的数据存入tableview的数据源
- (void)appendCacheToDataArray {
    
    __weak typeof (self) weakSelf = self;
    __strong typeof (weakSelf) strongSelf = weakSelf;
    
    if ([_messageBuffer count]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [weakSelf.dataMutableArray addObjectsFromArray:strongSelf->_messageBuffer];
            
            // 启动刷新列表的timer
            if (_scrollingTableViewTimer == nil && !weakSelf.manualScrolling && [strongSelf->_messageBuffer count]) {
                _scrollingTableViewTimer = [NSTimer timerWithTimeInterval:1 target:weakSelf selector:@selector(scrollingTableViewToBottom) userInfo:nil repeats:YES];
                [[NSRunLoop mainRunLoop] addTimer:_scrollingTableViewTimer forMode:NSRunLoopCommonModes];
                
            }
            
            [strongSelf->_messageBuffer removeAllObjects];
            
        });
    }
  
}

// 如果返回的数据是本机用户所发,则立即显示,不需要走缓冲策略,直接加入到tableview数据源,刷新列表
- (void)greenChannel:(NSDictionary *)item {
    __weak typeof (self) weakSelf = self;
    if (pthread_main_np() != 0) {
        // main thread
        [weakSelf caculateContentInset];
        YH_BarrageMsgModel *message = [[YH_BarrageMsgModel alloc]initWithDictionary:item error:nil];
        [weakSelf.dataMutableArray addObject:message];
        [weakSelf reloadData];
        CGPoint bottomOffset = CGPointMake(0, weakSelf.contentSize.height - weakSelf.bounds.size.height);
        [weakSelf setContentOffset:bottomOffset animated:YES];
    }else {
        dispatch_sync(dispatch_get_main_queue(), ^{
            [weakSelf caculateContentInset];
            YH_BarrageMsgModel *message = [[YH_BarrageMsgModel alloc]initWithDictionary:item error:nil];
            [weakSelf.dataMutableArray addObject:message];
            [weakSelf reloadData];
            CGPoint bottomOffset = CGPointMake(0, weakSelf.contentSize.height - weakSelf.bounds.size.height);
            [weakSelf setContentOffset:bottomOffset animated:YES];
        });
    }
    
}


- (void)scrollingTableViewToBottom {
    __weak typeof (self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [weakSelf caculateContentInset];
        
        // 做内存保护,数组内数据大于上限时强制清掉
        if (weakSelf.dataMutableArray.count >= MaxQueueCapacity) {
            [weakSelf.dataMutableArray removeAllObjects];
        }
        
        [weakSelf reloadData];

        CGPoint bottomOffset = CGPointMake(0, weakSelf.contentSize.height - weakSelf.bounds.size.height);
        [weakSelf setContentOffset:bottomOffset animated:YES];

        if (_scrollingTableViewTimer) {
            [_scrollingTableViewTimer invalidate];
            _scrollingTableViewTimer = nil;
        }
        
    });
}


// 自动更新tableview
- (void)startAutoScolling
{
    self.manualScrolling = NO;
    self.newMsgCount = 0;
    [self appendCacheToDataArray];
    
    CGPoint bottomOffset = CGPointMake(0, self.contentSize.height - self.bounds.size.height);
    [self setContentOffset:bottomOffset animated:YES];
    
    if ([self.barrageScrollingDelegate respondsToSelector:@selector(autoScollingCallback)]) {
        [self.barrageScrollingDelegate autoScollingCallback];
    }
    
    
    if (_scrollingTableViewTimer == nil) {
        _scrollingTableViewTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(scrollingTableViewToBottom) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_scrollingTableViewTimer forMode:NSRunLoopCommonModes];
    }
}


// 判断tableview是否滑到底部
- (BOOL)isLastTableViewCell {
    return (self.contentOffset.y >= (self.contentSize.height - self.frame.size.height));
}

// 通过设置contentInset 实现cell从下至上‘生长’动画
- (void)caculateContentInset
{
    CGSize contentSize = self.contentSize;
    CGFloat tableViewHeight = CGRectGetHeight(self.frame);
    
    if (contentSize.height <=  tableViewHeight) {
        
        CGFloat contentHeight = contentSize.height;
        [self setContentInset:UIEdgeInsetsMake(tableViewHeight-contentHeight, 0, 0, 0)];
    } else {
        [self setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    
}

- (void)compare:(NSDictionary *)newItem {
    NSDictionary *oldItem = [self.dataMutableArray lastObject];
    long oldItemCmd = [[oldItem objectForKey:@"cmd"] longValue];
    long newItemCmd = [[newItem objectForKey:@"cmd"] longValue];
    
    if (oldItem && oldItemCmd == newItemCmd && oldItemCmd == 4) {
        self.isMutipleJoin = YES;
    } else {
        self.isMutipleJoin = NO;
    }
}


#pragma mark - User respond

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.manualScrolling = YES;
    if (_scrollingTableViewTimer) {
        [_scrollingTableViewTimer invalidate];
        _scrollingTableViewTimer = nil;
    }
  
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    NSLog(@"%s", __func__);
    
    if ([self isLastTableViewCell]) {
        [self startAutoScolling];
    }
    
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([self isLastTableViewCell]) {
        [self startAutoScolling];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataMutableArray count];
}

- (NSInteger)numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 44.0f;
    
    YH_BarrageMsgModel *message  = [self.dataMutableArray objectAtIndex:indexPath.row];
    
    if (message) {
      
        if (message.cmd == 5) {
            return [YH_BarrageMsgCell cellHeightWithMessage:message];
        } else {
            return 26;
        }
    }
    
    return 44;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    YH_BarrageMsgModel *message  = [self.dataMutableArray objectAtIndex:indexPath.row];
    
    
    if (message.cmd == 5) { // 聊天消息
        YH_BarrageMsgCell *cell = [self dequeueReusableCellWithIdentifier:kMessageCellID];
        if (cell == nil) {
            cell = [[YH_BarrageMsgCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kMessageCellID];
        }

        [cell updateCellWithMessage:message cellWidth:CGRectGetWidth(tableView.frame)];
        
        return cell;
        
    } else if(message.cmd == 4) {
        // 用户加入
        YH_BarrageJoinCell *cell = [self dequeueReusableCellWithIdentifier:kJoinCellID];
        if (cell == nil) {
            cell = [[YH_BarrageJoinCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kJoinCellID];
        }
        cell.msgModel = message;
        
        return cell;
    }
    
    return nil;

}


#pragma mark - UITableViewDelegate

#pragma mark - getters and setters

// 读操作同步
- (NSMutableArray *)dataMutableArray
{
    __block __weak  NSMutableArray *localDataMutableArray;
    dispatch_sync(_syncQueue, ^{
        localDataMutableArray = _dataMutableArray;
    });
    
    return localDataMutableArray;
}

// 写操作异步(且读操作完成后进行)
-(void)setDataMutableArray:(NSMutableArray *)dataMutableArray
{
    dispatch_barrier_async(_syncQueue, ^{
        _dataMutableArray = dataMutableArray;
    });
}


@end