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

即使app在后台,我想使用以下function?

- (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在后台调用?

我刚才处理类似的问题。 要记住几件重要的事情:

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

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

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

iOS应用程序如何在后台无限期地保持TCP连接活动?

我最终使用了voip(就像你一样)并按照这里的建议播放静音音频循环 – 它有效。 不确定这个静音音频循环是否仍然是必要的。

当iOS应用程序进入后台时,TCP和UDP(与多播)连接会发生什么

请务必阅读开发VoIP应用程序和技术说明TN2277的提示:网络和多任务处理