ios – NSNotification中的观察者(itemDidFinishPlaying)随机调用两次

视频播放完毕后,我正在显示文本.我正在使用通知技术来实现这一目标.唯一的问题是Observer每隔一段时间被调用两次.它触发“itemDidFinishPlaying”两次(因此同名的方法).我无法预测何时.我不知道为什么.它看起来是随机的(我知道这听起来很奇怪)就好像它工作得很好让我们说连续15次,然后下一次这种行为突然发生了.我做了一个重建并运行应用程序,这次它连续运行19次,然后两次调用Observer等等……不可预测.我已经尝试过每个场景来预测bug以便修复它.到目前为止,这是不可能的.所以我有2个问题.

1)为什么会发生并“随机”?

2)如何解决这个双重调用问题?

这两个以下的对话也没有帮助:

Why the Observer in NSNotification called twice….?

How to stop the Observer in NSNotification to called twice?

请在下面找到我的代码

- (void) playAnimation: (Nsstring *) theString {

UIView *thisCurrentView = self.currentView;
UIView *thisReplacementView = [[UIView alloc] init];

//[avPlayer pause];
[self replaceView: thisCurrentView withView: thisReplacementView];

Nsstring *filepath = [[NSBundle mainBundle] pathForResource:theString ofType:@"mov"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];


 // First create an AVPlayerItem
 AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:fileURL];

 // Subscribe to the AVPlayerItem's DidplayToEndTime notification.
[[NSNotificationCenter defaultCenter] addobserver:self selector:@selector(itemDidFinishPlaying) name:AVPlayerItemDidplayToEndTimeNotification object:playerItem];

 // Pass the AVPlayerItem to a new player
 controlledplayer = [[AVPlayer alloc] initWithPlayerItem:playerItem];


AVPlayerLayer *animatedLayer = [AVPlayerLayer playerLayerWithPlayer:controlledplayer];


[animatedLayer setFrame:CGRectMake(0,1024,1024)];
[thisReplacementView.layer addSublayer: animatedLayer];


// Begin playback
[controlledplayer play];

// Clear some content
[self displayNoContent];

pageContent = theString;


playingStatus = YES;

}

– (void)itemDidFinishPlaying {

[self displayContent: pageContent];

}

解决方法

试试这个,
-(void)itemDidFinishPlaying {

      [self displayContent: pageContent];
      [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidplayToEndTimeNotification object:playerItem];

}

它可能适合你.

EDIT1:

在设置新方案之前,每次都要删除通知观察者.尝试下面的方案.它将确保删除一个观察者(即使它不存在也没问题)并添加新的观察者.

// Subscribe to the AVPlayerItem's DidplayToEndTime notification.

[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidplayToEndTimeNotification object:playerItem];
[[NSNotificationCenter defaultCenter] addobserver:self selector:@selector(itemDidFinishPlaying) name:AVPlayerItemDidplayToEndTimeNotification object:playerItem];

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...