UIApplicationDidBecomeActiveNotification 不调用

UIApplicationDidBecomeActiveNotification not calling

我正在使用以下代码来检测我的 viewcontroller 从后台显示的时间:

    - (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
// some other codes
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backsFromBackground:) name:UIApplicationDidBecomeActiveNotification object:self];

}

和:

    - (void) backsFromBackground:(NSNotification *) notification
{
    //Do something

}

和:

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self  name:UIApplicationDidBecomeActiveNotification object:self];

}

但是观察者没有调用并且方法 backsFromBackground: 没有调用。有人知道吗?

更改此行

[[NSNotificationCenter defaultCenter] addObserver:self
  selector:@selector(backsFromBackground:)
  name:UIApplicationDidBecomeActiveNotification
  object:self];

[[NSNotificationCenter defaultCenter] addObserver:self 
  selector:@selector(backsFromBackground:)
  name:UIApplicationDidBecomeActiveNotification
  object:nil];

NSNotificationCenter订阅中的最后一个object参数是通知发送者,即你要观察的对象。更改不是来自您的视图控制器 (self),而是来自 UIApplication.

您可以传入 [UIApplication sharedApplication],但因为 UIApplication 只有一个实例,所以您可以将 object 参数保留为 nil。

您也会希望在 removeObserver 代码中执行相同的操作。

请试试这个:notificationSender 在您的情况下必须是 nil

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // some other codes
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backsFromBackground:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

来自Apple Documentation:最后一个参数是你的notificationSender:

The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer.

If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.