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)