9

我需要知道应用程序何时处于前台,它处于活动状态还是非活动状态?

如果我的应用程序处于非活动状态,我需要触发注销协议并销毁当前用户的会话,

- (void)applicationWillResignActive:(UIApplication *)application
{
    NSLog(@"App is not active logout success");
}

是否有任何 appDelegate 方法告诉我应用程序处于非活动状态,任何代码示例都会对我有很大帮助。

如果需要使用“NSNotificationCenter”,我可以在哪个类中添加代码以及谁将成为观察者。

4

2 回答 2

8

要测试状态,您可以执行以下操作:

[[UIApplication sharedApplication] applicationState]==UIApplicationStateInactive

或者

[[UIApplication sharedApplication] applicationState]==UIApplicationStateActive

如果您想收到通知,您可以执行以下操作:

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

或者

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(yourselector:)
                                                 name:UIApplicationDidEnterBackgroundNotification object:nil];

你也可以做其他通知(来自https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/):

UIApplicationDidBecomeActiveNotification UIApplicationDidChangeStatusBarFrameNotification UIApplicationDidChangeStatusBarOrientationNotification UIApplicationDidEnterBackgroundNotification UIApplicationDidFinishLaunchingNotification UIApplicationDidReceiveMemoryWarningNotification UIApplicationProtectedDataDidBecomeAvailable UIApplicationProtectedDataWillBecomeUnavailable UIApplicationSignificantTimeChangeNotification UIApplicationUserDidTakeScreenshotNotification UIApplicationWillChangeStatusBarOrientationNotification UIApplicationWillChangeStatusBarFrameNotification UIApplicationWillEnterForegroundNotification UIApplicationWillResignActiveNotification UIApplicationWillTerminateNotification UIContentSizeCategoryDidChangeNotification

如果要使用应用委托,可以使用:

- (void)applicationDidEnterBackground:(UIApplication *)application {}

或者

- (void)applicationDidBecomeActive:(UIApplication *)application {}
于 2015-01-22T06:41:43.030 回答
0

请参阅此 Apple Doc:应用程序生命周期

applicationDidBecomeActive:—让你的应用知道它即将成为前台应用。使用此方法进行最后一分钟的准备。

applicationWillResignActive:—让您知道您的应用正在从前台应用过渡。使用此方法可将您的应用程序置于静止状态。

applicationWillEnterForeground:- 让您知道您的应用程序正在离开后台并回到前台,但它尚未处于活动状态。

applicationWillTerminate:—让您知道您的应用程序正在被终止。如果您的应用程序被暂停,则不会调用此方法

于 2015-01-22T06:53:04.503 回答