2011-10-09 26 views
10

我有一個voip應用程序,它在後臺運行不斷。 雖然我在後臺我正在從主線程調用:(建立網絡連接,以防我診斷網絡丟失)。PerformSelector延遲後不運行在後臺模式 - iPhone

[self performSelector :@selector(Reconnect:) withObject:nil afterDelay:60.0]; 

但是,選擇器只在我的應用程序返回到前景時執行。 我應該做什麼特別讓選擇器在後臺執行嗎?

感謝

編輯:

-(void) reconectInBackgroundAfterDelay:(NSTimeInterval) dealy 
{ 
    NSLog(@"reconectInBackgroundAfterDelay"); 
    UIApplication* app = [UIApplication sharedApplication]; 

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
     [app endBackgroundTask:bgTask]; 
     bgTask = UIBackgroundTaskInvalid; 
    }]; 

    // Start the long-running task and return immediately. 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

     [self performSelector :@selector(Reconnect:) withObject:nil afterDelay:dealy]; 

     [app endBackgroundTask:bgTask]; 
     bgTask = UIBackgroundTaskInvalid; 
    }); 
} 

我加入這個代碼,而不是,但仍然是「重新連接」的方法是沒有得到所謂的提供延遲之後。 我在後臺調用「reconectInBackgroundAfterDelay」方法。

其他建議?

編輯2 找到了解決辦法。見下面

回答

22

我迄今發現的唯一解決辦法:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

     NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(Reconnect:) userInfo:nil repeats:NO];  

     [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode]; 

     [[NSRunLoop currentRunLoop] run]; 
    }); 
+0

非常感謝,它運作良好。 – 2011-11-01 06:34:40

+0

我的應用程序也是voip應用程序。但最初我的應用程序在註冊之前先從服務器上下載文件。是否有可能使用您的解決方案繼續下載。 –

+0

這裏是[http://stackoverflow.com/questions/14828955/download-files-using-http-request-in-background-in-iphone-above-ios-4-0#comment20777172_14828955] [我的問題] –

1

你把這條線放在beginBackgroundTaskWithExpirationHandler塊嗎?看看第完成後臺有限長任務http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html

+0

我沒有使用後臺任務,我的應用程序是一個voip應用程序,所以它可以在後臺不斷運行,保持持久的網絡連接。在這裏沒有看到使用後臺任務的原因,也看不出它會如何幫助。 – Idan

+0

VoIP應用程序不會在後臺不斷運行。從[iOS應用程序編程指南](http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH5- SW15):「系統不會始終保持VoIP應用程序的喚醒狀態,而是允許系統暫停並提供監視其插座的設施。當檢測到傳入流量時,系統喚醒VoIP應用程序並返回其套接字的控制權到它「。 – omz

+0

好的,假設我在後臺丟失了tcp連接,並且我想在2分鐘後安排一個選擇器來重新建立連接。如果執行選擇後延遲不會這樣做,我該如何實現它?顯然後臺任務不適合這裏。 – Idan

1

我測試了一段時間,發現在IOS後臺運行時corebluetooth事件來了,如果你想要做的事延遲使用的NSTimer對象,你必須少於10秒,如果超過10秒,計時器將失效。

+1

這裏10秒的意義是什麼?你能否以合理的方式解釋它? – Swamy

+0

很抱歉這麼晚纔回復,讓我舉一個例子 請看下面的代碼,如果DELAY_EVENT_TIME超過10個,這DoSomething的FUNC不會被稱爲 的#define DELAY_EVENT_TIME 8 - (空)centralManager:(CBCentralManager *)中央didConnectPeripheral:(CBPeripheral *)peripheral {NSTimer scheduledTimerWithTimeInterval:DELAY_EVENT_TIME target:self selector:@selector(doSomething)userInfo:nil repeats:NO]; (無效)doSomething { \t} NSLog(@「doSomething delay!」); } – DDZ