1. 程式人生 > 其它 >如何快速的開發一個完整的iOS直播app(點贊功能)

如何快速的開發一個完整的iOS直播app(點贊功能)

客戶端程式碼

  • 點選小紅心,傳送socket給伺服器,並且要傳遞房間Key給伺服器,通知給哪個主播點贊,就能傳入到對應的分組socket中
  • 怎麼傳遞房間key,房間Key在主播介面,一般一個客戶端,只會產生一個房間,可以記錄到socket物件中
  • 業務邏輯:使用者點選小紅心,小紅心就會往上慢慢飄。
  • 實現原理:其實就是一個動畫。
  • 怎麼實現:用UIView做不了,因為小紅心是不規則的左右擺動,慢慢上去的。
  • 可以使用核心動畫(建立CALayer),CABasicAnimation和CAKeyframeAnimation,放在一個group組中。
  • CABasicAnimation:漸漸顯示動畫,修改透明度
  • CAKeyframeAnimation:做路徑動畫,描述小紅心的路徑,然後按照這個路徑走.
    • 描述一根線,x從寬度中獲取隨機值,y值每次減減
  • 動畫完成,記得移除,可以用動畫事務類,監聽動畫是否完成,程式碼一定要放在最前面
XMGLiveOverlayViewController.m

- (IBAction)clickUpvote:(id)sender {
    
    // 傳送點贊事件
    [[SocketIOClient clientSocket] emit:@"upvote" with:@[[SocketIOClient clientSocket].roomKey]];
    
}


XMGUpVoteViewController.m
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[SocketIOClient clientSocket] on:@"upvote" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
       // 監聽到點贊,進行點贊動畫
        [self setupVoteLayer];
    }];
    
}

- (void)setupVoteLayer
{
    CALayer *layer = [CALayer layer];
    layer.contents = (id)[UIImage imageNamed:@"hearts (1)"].CGImage;
    [self.view.layer addSublayer:layer];
    layer.bounds = CGRectMake(0, 0, 30, 30);
    layer.position = CGPointMake(self.view.width * 0.5, self.view.height);
    
    [self setupAnim:layer];
}

- (void)setupAnim:(CALayer *)layer
{
    [CATransaction begin];
    
    [CATransaction setCompletionBlock:^{
        [layer removeAllAnimations];
        [layer removeFromSuperlayer];
    }];
    
    // 建立basic動畫
    CABasicAnimation *alphaAnim = [CABasicAnimation animation];
    alphaAnim.keyPath = @"alpha";
    alphaAnim.fromValue = @0;
    alphaAnim.toValue = @1;
    
    // 路徑動畫
    CAKeyframeAnimation *pathAnim = [CAKeyframeAnimation animation];
    pathAnim.keyPath = @"position";
    pathAnim.path = [self animPath].CGPath;
    
    
    // 建立動畫組
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.animations = @[alphaAnim,pathAnim];
    group.duration = 5;
    [layer addAnimation:group forKey:nil];
    
    
    
    [CATransaction commit];
}


- (UIBezierPath *)animPath
{
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    CGFloat y = self.view.height;
    CGFloat x = self.view.width * 0.5;
    while (y > 0) {
        x = arc4random_uniform(self.view.width -