2013-02-14 33 views
6

使用iPhone應用程序聊天的Iam使用套接字連接與服務器進行通信。當應用程序移動到後臺時,我可以看到服務器能夠與應用程序通信約5分鐘。但在此之後,套接字連接被破壞。但是,應用程序一旦移動到後臺就會停止執行。爲什麼套接字連接保持5分鐘,而不是應用程序執行。蘋果是否指定了連接的確切時間。iOS應用程序轉到後臺後導致套接字連接中斷

+0

您的應用程序是否已註冊爲VoIP應用程序? – trojanfoe 2013-02-14 14:00:23

+0

nope。它沒有註冊爲Voip。 – Chinta 2013-02-20 04:02:33

回答

9

您可以通過使用利用的下面的代碼在applicationDidEnterBackground獲得600秒(10分鐘)的最大時間:

if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E 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 
    }); 
    } 
} 

文檔可以在這裏找到http://disanji.net/iOS_Doc/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

我剛剛實施的backgroundTaskIdentifier對象並使無效background_task檢查時間,應用程序是活着的,並運行600秒。您甚至可以通過使用此功能獲得剩餘時間

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

如果您的目標是iOS 4.3或更高版本,則不需要兩個初始if語句。 – rmaddy 2013-02-14 18:53:53

+0

@rmaddy你是對的:) – 2013-02-15 04:32:08

+0

@chinta在這裏可以找到配置VoIP使用套接字的背景。非常翔實的http://wiseman-safiq.blogspot.in/2010/11/ios-executing-code-in-background.html – 2013-02-15 04:37:28

1

從蘋果公司的IOS Programming Guide

是進入後臺時,大多數應用程序移動到 暫停狀態之後不久。在此狀態下, 應用程序不會執行任何代碼,並且可能隨時從內存中刪除 。爲用戶 提供特定服務的應用程序可以請求後臺執行時間,以便提供這些服務。

這至少可以解釋爲什麼應用程序停止執行。爲什麼您的服務器仍然能夠與您的應用程序通信5分鐘,可能是因爲您設置了一個額外的很長時間,並且沒有在您的應用程序進入後臺時明確關閉套接字連接。

相關問題