2013-12-13 23 views
7

我想知道我的应用何时会被暂停?在一段时间内不活跃或被用户终止的状态。我需要这个,因为我需要关闭一个web套接字的连接。不过,我希望在应用程序处于后台状态时保持连接处于活动状态。iOS:如何判断应用何时会暂停?

我该怎么做?

感谢

编辑:这是一个不重复的问题,其他的问题,希望即将当应用程序不再是活动的,我想知道应用程序已终止。

+2

@ dandan78这只是为了进入后台,我想要一个通知,当应用程序被暂停。 –

回答

-1

在您的AppDelegate.m文件中,当用户点击主页按钮并且应用程序将转到后台时(这里您可以保持连接正常运行,但您应该阅读有关后台任务的Apple文档,因为你的连接不能长生不老,如果应用程序仍然在后台还有其他的方法来保持你的应用程序的最新像推送通知等)更新:

- (void)applicationWillResignActive:(UIApplication *)application 
{ 
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 
} 

这种方法将被调用应用程序时将被终止(完全从多任务中关闭)。

- (void)applicationWillTerminate:(UIApplication *)application 
{ 
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
} 

您可以在此方法中处理您的连接。

+0

好吧,谢谢这个作品。我试过这个,它效果很棒! –

+9

“暂停”不是“背景”。 – Almo

+0

我可以澄清一下,因为我对此有点困惑,applicationWillTerminate会在应用程序长时间处于后台并且iOS杀死应用程序时被调用?我有一个应用程序在后台10分钟后重新启动,如果您从后台返回它。 –

3

您还可以添加通知观察者

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(receiveSuspendNotification:) 
              name:UIApplicationWillResignActiveNotification 
              object:nil]; 

- (void) receiveSuspendNotification:(NSNotification*)notif 
{ 
} 

方法将被调用,您可以执行所需的任务。

+0

为什么在使用'NikosM.'答案中的方法时向通知中心添加通知观察者。看起来有点多余添加另一个电话是不是。 – Popeye

+1

我发现通知是一个更清洁的方法,如果你正在做的应用程序委托以外的地方。 – zekel

+0

http://stackoverflow.com/users/980097/popeye,因为它不起作用。截至2017年,这表明应用程序何时移动到后台,但不会在它停留在后台几分钟后暂停。 –

-2

如果您的应用程序未在后台注册运行,那么当您收到UIApplicationDidEnterBackgroundNotification时,您的应用程序将被暂停在RAM中。