2011-10-09 25 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