Hi I am playing video on my UITableViewCells using AVPlayer, It was working fine on iOS 7, but in iOS8 it crashing with following error.
'An instance 0x7c01b000 of class AVPlayerItem was deallocated while key value observers were still registered with it.
Here is my code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
.........
.........
if(cell.videoPlayer!= nil && cell.videoPlayer.currentItem != nil)
{
[cell.videoItem removeObserver:self forKeyPath:@"playbackBufferEmpty" context:nil];
[cell.videoItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp" context:nil];
}
cell.videoPlayer = [AVPlayer playerWithPlayerItem:cell.videoItem];
cell.avLayer = [AVPlayerLayer playerLayerWithPlayer:cell.videoPlayer];
cell.videoPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
[cell.videoItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionInitial context:nil];
[cell.videoItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionInitial context:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidBufferPlaying:) name:AVPlayerItemPlaybackStalledNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
cell.avLayer.frame = CGRectMake(5, 9, 310, 310);
[cell.contentView.layer addSublayer: cell.avLayer];
[ cell.videoPlayer play];
[cell.contentView addSubview:cell.videoActivity];
return cell;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
NSArray* cells = homeTabl.visibleCells;
for (HomeCell* cell in cells) {
if (object == cell.videoItem && [keyPath isEqualToString:@"playbackBufferEmpty"]) {
if (cell.videoItem.playbackBufferEmpty) {
NSLog(@"buffering");
cell.videoActivity.hidden = NO;
}
}
else if (object == cell.videoItem && [keyPath isEqualToString:@"playbackLikelyToKeepUp"])
{
if (cell.videoItem.playbackLikelyToKeepUp)
{
cell.videoActivity.hidden = YES;
[cell.videoPlayer play];
}
}
}
}
-(void)scrollViewDidScroll:(UIScrollView *)aScrollView {
NSArray* cells = homeTabl.visibleCells;
for (HomeCell* cell in cells) {
[cell.videoPlayer pause];
[cell.avLayer removeFromSuperlayer];
cell.videoPlayer = nil;
cell.videoItem = nil;
}
What could be the reason ? I have gone through this SO question, but I could not implement this in my codes. Please help me to fix this.