iOS:如何判断应用程序何时暂停?

时间:2013-12-13 06:07:19

标签: ios objective-c background suspend application-state

我想知道我的应用何时暂停?在一定时间内未被激活或被用户终止的状态。我需要这个,因为我需要关闭一个Web套接字的连接。我希望在应用程序处于后台状态时保持连接处于活动状态。

我该怎么做?

由于

编辑:这不是一个重复的问题,其他问题是关于应用何时不再有效,我想知道该应用已被终止。

3 个答案:

答案 0 :(得分:4)

您还可以添加通知观察者

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

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

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

答案 1 :(得分:-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:.
}

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

答案 2 :(得分:-2)

如果你的应用没有注册在后台运行,那么当收到UIApplicationDidEnterBackgroundNotification时,你的应用将暂停在RAM中。