如何在应用程序处于后台时处理套接字连接的事件?

时间:2012-06-14 12:08:10

标签: iphone ios sockets background multitasking

即使app在后台,我也想使用以下功能?

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
 {
        case NSStreamEventHasBytesAvailable:
        {  NSLog(@"Event:NSStreamEventHasBytesAvailable");
            if (theStream == _inputStream) {

                NSLog(@"NSStreamEventHasBytesAvailable: on Input Stream");
                uint8_t buffer[1024];
                int len;

                while ([_inputStream hasBytesAvailable]) {
                    len = [_inputStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0) {

                        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

                        if (nil != output) {

                            NSLog(@"server said: %@", output);
                             // to get local notification I am calling below method.
 [self scheduleNotification];       
                        }
                    }
                }
            }
            break;
        }

以上代码在foreGround中完成。我已经在apple文档中给出了所有更改,以在后台模式中运行应用程序 - voip。 我应该在AppDelegate方法中写什么?

- (void)applicationDidEnterBackground:(UIApplication *)application
{
}

如何获取流:在后台调用handleEvent?

2 个答案:

答案 0 :(得分:7)

前一段时间我正在处理类似的问题。要记住几件重要的事情:

  • 背景“voip”功能仅适用于设备 - 请勿使用模拟器进行测试
  • 如果您的应用程序注册为voip应用程序并且不是真正的voip应用程序,您可能会(已测试)被拒绝

因此,如果这不是voip应用程序,您可能实际上想要使用远程通知直接提醒用户而不是显示本地通知。我想这是您的应用程序通过App Store验证的唯一方式。

无论如何,SO上的两个链接可以帮助您找到帮助:

How can an iOS app keep a TCP connection alive indefinitely while in the background?

我最终使用了voip(正如你所做的那样)并按照这里的建议播放静音音频循环 - 它有效。不知道 这个无声的音频循环仍然是必要的。

What happens to TCP and UDP (with multicast) connection when an iOS Application did enter background

请务必阅读Tips for Developing a VoIP AppTechnical Note TN2277:Networking and Multitasking

答案 1 :(得分:0)

使用此代码可使您的应用在ios中保持活动状态

var backgroundUpdateTask: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0)

func endBackgroundUpdateTask() {
    UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
    self.backgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
}
func applicationWillResignActive(_ application: UIApplication) {
    self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
        self.endBackgroundUpdateTask()
    })
}
func applicationDidBecomeActive(_ application: UIApplication) {
    self.endBackgroundUpdateTask()

}

我希望您能通过此帮助获得成功

相关问题