10

我有一个 voip 应用程序,它也在后台不断运行。当我在后台时,我从主线程调用:(建立网络连接以防我诊断出网络丢失)。

[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 找到了解决方案。见下文

4

3 回答 3

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]; 
    }); 
于 2011-10-10T14:13:26.463 回答
1

我测试了一段时间,发现在ios后台运行corebluetooth事件来的时候,如果你想做一些延迟使用NSTimer对象,你必须小于10秒,如果超过10秒,定时器会无效的。

于 2013-07-04T04:19:17.673 回答
1

你把这条线放在beginBackgroundTaskWithExpirationHandler块里了吗?查看http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html后台完成有限长度任务部分。

于 2011-10-09T13:43:11.540 回答