套接字连接在iOS应用程序转到后台后死亡

Iam使用iPhone应用程序聊天使用套接字连接与服务器进行通信。 当应用程序移动到后台时,我可以看到服务器能够与应用程序进行通信约5分钟。 但在此之后,套接字连接被破坏。 但是,应用程序一旦移动到后台就会停止执行。为什么套接字连接保持5分钟,而不是应用程序的执行。苹果是否指定了连接的确切时间。

通过在applicationDidEnterBackground中使用以下代码,您可以获得600秒(10分钟)的最大时间:

if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking IE iOS 4 if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance __block UIBackgroundTaskIdentifier background_task; //Create a task object background_task = [application beginBackgroundTaskWithExpirationHandler: ^ { [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks background_task = UIBackgroundTaskInvalid; //Set the task to be invalid //System will be shutting down the app at any point in time now }]; //Background tasks require you to use asyncrous tasks dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //Perform your tasks that your application requires NSLog(@"\n\nRunning in the background!\n\n"); [application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform background_task = UIBackgroundTaskInvalid; //Invalidate the background_task }); } } 

文档可以在这里findhttp://disanji.net/iOS_Doc/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

我只是实现了backgroundTaskIdentifier对象和无效的background_task来检查时间,应用程序是活着的,并运行600秒。 你甚至可以通过使用这个来获得剩余的时间

 NSLog(@"Time remaining: %f", application.backgroundTimeRemaining); 

从苹果的IOS编程指南

大多数进入后台状态的应用程序都会在此后不久移到暂停状态。 在此状态下,应用程序不会执行任何代码,并可能随时从内存中删除。 为用户提供特定服务的应用程序可以请求后台执行时间以提供这些服务。

这至less解释了为什么应用程序停止执行。 为什么你的服务器仍然能够与你的应用程序通信5分钟,因为你设置了一个额外的时间,并没有明确地closures你的应用程序进入后台的套接字连接。