如何确定应用程序处于活动状态还是非活动状态ios?

时间:2015-01-22 06:37:57

标签: ios objective-c lifecycle user-inactivity

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

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

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

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

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

2 个答案:

答案 0 :(得分: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

如果您想使用app delegate,可以使用:

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

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

答案 1 :(得分:0)

请参阅此Apple Doc:App Life Cycle

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

applicationWillResignActive: - 让您知道您的应用正在转变为前台应用。使用此方法可将应用程序置于静止状态。

applicationWillEnterForeground: - 让您知道您的应用已移出背景并返回到前台,但它尚未激活。

applicationWillTerminate: - 让您知道您的应用已被终止。如果您的应用被暂停,则不会调用此方法