1

我正在使用今天的小部件(使用 Swift)编写我的第一个 iOS 应用程序。我想知道是否有一个函数在我的应用程序在关闭通知中心后回到前台时被调用。

我知道我可以使用观察者进行检查,UIApplicationWillEnterForegroundNotification但是在使用我的应用程序并再次关闭它时拉下通知中心时不会调用我的函数。

我的问题很简单:用户不太可能拉下通知中心来操作我在应用程序中使用的数据,但我仍然必须考虑如果他们这样做会发生什么。用户应该能够通过按下今天小部件按钮来保存他的当前位置。

如果在使用我的应用程序时发生这种情况,该应用程序将不会检查新数据。

4

1 回答 1

2

我使用以下代码来确定通知中心是否在应用程序运行时打开:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{
    BOOL notificationCenterCurrentlyDisplayed;
}

- (void) viewDidLoad
{
    [super viewDidLoad];
    notificationCenterCurrentlyDisplayed = false;
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(onNotificationCenterDisplayed) name:UIApplicationWillResignActiveNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(onNotificationCenterDismissed) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void) onNotificationCenterDisplayed
{
    notificationCenterCurrentlyDisplayed = true;
    NSLog(@"Notification center has been displayed!");
}

- (void) onNotificationCenterDismissed
{
    // Reason for this check is because once the app is launched the UIApplucationDidBecomeActiveNotification is called.
    if (notificationCenterCurrentlyDisplayed)
    {
        notificationCenterCurrentlyDisplayed = false;
        NSLog(@"Notification center has been dismissed!");
    }
}
@end

此外,当用户决定将应用程序关闭到后台时,也会调用通知中心显示方法。

于 2015-02-04T21:59:44.463 回答