I want to display videos in UITableView like Instagram that will play automatically when the cell is visible and pause when cell disappears from screen. I tried everywhere to find solution but all I found is very complex code to even understand. At the moment two cell is displayed on screen. Only one video should play and all other should stop.
I also need to care about memory leaks. So I don't know where I can allocate AVPlayerViewController. I deal with array of URLs to play videos.
Please give me perfect solution in detail. Help will be appreciated.
EDIT:
This method gives index array which are displayed on the screen
-(BOOL)isRowVisible :(NSIndexPath*)indexPath {
NSArray *indexes = [tblHome indexPathsForVisibleRows];
for (NSIndexPath *index in indexes) {
if (index.row == indexPath.row) {
return YES;
}
}
return NO;
}
In cellForRowAtIndexpath method-
BOOL visibleCell = [self isRowVisible:indexPath];
if(visibleCell == YES)
{
//if(!avpController)
{
avpController = nil;
avpController= [[AVPlayerViewController alloc] init];
avpController.player=videoPlayer;
// avpController.view.frame = CGRectMake(0, 50, SCREEN_WIDTH, 100); //CGRectMake(0, userDetailView.frame.origin.y + userDetailView.frame.size.height +5, SCREEN_WIDTH, 200) ;
avpController.view.frame = videoView.bounds;
[videoView addSubview:avpController.view];
}
NSURL *url= [NSURL URLWithString:[arrVideo valueForKey:@"video_path"]];
videoPlayer = [AVPlayer playerWithURL:url];
[videoPlayer addObserver:self forKeyPath:@"status" options:0 context:nil];
[videoPlayer play];
}