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

Jas*_*man 7 background objective-c suspend application-state ios

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

我该怎么做呢?

谢谢

编辑:这不是一个重复的问题,其他问题是关于应用程序不再活动时,我想知道该应用程序已被终止.

Nik*_* M. -4

在您的 AppDelegate.m 文件中,当用户点击主页按钮时,将调用此方法,并且应用程序将转到后台(在这里您可以保持连接处于活动状态,但您应该阅读有关后台任务的苹果文档,因为您的连接无法如果应用程序保留在后台,则永远存在。还有其他方法可以使您的应用程序保持最新状态,例如推送通知更新等):

- (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.
}
Run Code Online (Sandbox Code Playgroud)

当应用程序终止(从多任务处理中完全关闭)时,将调用此方法。

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

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

  • “暂停”不是“背景”。 (16认同)
  • 这是完全错误的。这表明您的应用程序何时进入后台,而不是何时暂停。 (5认同)
  • @jeraldo不,你无法知道你的应用程序何时从后台状态转变为挂起状态。iOS 不会“杀死”应用程序,请参阅 https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html (3认同)