gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:43:42 25 4
gpt4 key购买 nike

我在视频播放完毕后立即显示文本。我正在使用一种通知技术来实现这一点。唯一的问题是 Observer 不时被调用两次。它会触发“itemDidFinishPlaying”两次(因此会触发同名方法)。我无法预测什么时候。我不知道为什么。它看起来是随机的(我知道这听起来很奇怪)就像它工作正常一样,假设连续 15 次,下一次这种行为突然发生。我重建并运行应用程序,这次它连续运行 19 次,然后两次调用观察者,等等......不可预测。我已经尝试了所有场景来预测错误以修复它。到目前为止这是不可能的。所以我有 2 个问题。

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

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

此外,以下 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, 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];

}

它可能对你有用。

编辑 1:

每次设置新的通知观察者之前,请删除通知观察者。尝试下面的场景。它将确保删除以前的观察者(即使它不存在也没有问题)并添加新的观察者。

// 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 - NSNotification (itemDidFinishPlaying) 中的观察者随机调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16248496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com