Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Play video within given frame or in UICollectionViewCell/UITableViewCell

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4.28k
    Comment on it

    Hi Readers,

    Usually we have scenarios for playing videos within the app. MPMoviePlayerController will be used for that. But you can see MPMoviePlayerController deprecated in iOS 9 and later. So we need to put our focus on AVPlayer now. With AVPlayer either we can play video in different screen with the help of AVPlayerViewController or we can play it within a frame into any view or cell. Following code can be used to play video into an UICollectionView:

     NSURL *videoURL = [NSURL URLWithString:@"http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"];
        AVPlayer *player = [AVPlayer playerWithURL:videoURL];
        AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
        UICollectionViewCell *cell = [_colView cellForItemAtIndexPath:indexPath];
        playerLayer.frame = cell.contentView.bounds;
        [cell.contentView.layer addSublayer:playerLayer];
        [player play];
    

    You will need to import following classes:

    #import <MediaPlayer/MediaPlayer.h>
    #import <AVFoundation/AVPlayer.h>
    #import <AVFoundation/AVPlayerLayer.h>

    You can see here that we are playing around with layer of our view and AVPlayerLayer. After adding its layer, we can see its working in content view frame of cell. You can pass any given view frame and layer accordingly.

    Following code can be used to play video with other screen using AVPlayerViewController:

    NSURL *videoURL = [NSURL URLWithString:@"http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"];
    AVPlayer *player = [AVPlayer playerWithURL:videoURL];
    AVPlayerViewController *playerViewController = [AVPlayerViewController new];
    playerViewController.player = player;
    [self presentViewController:playerViewController animated:YES completion:nil];

    Above code present AVPlayerViewController which plays video with URL.

    Hope it will help. Happy Coding.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: