嗨,我正在使用 AVPlayer 在我的 UITableViewCells 上播放视频,它在 iOS 7 上运行良好,但在 iOS8 中它因以下错误而崩溃。
'An instance 0x7c01b000 of class AVPlayerItem was deallocated while key value observers were still registered with it.
这是我的代码
- (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;
}
可能是什么原因 ?我已经完成了这个 SO question,但我无法在我的代码中实现它。请帮我解决这个问题。