即使应用程序在后台,我也想使用以下功能吗?
- (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中完成。我已经做出了苹果文档中所有的更改,以在后台模式下运行该应用程序-voip。我应该用AppDelegate方法写什么?
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
如何获取在后台调用的stream:handleEvent?
不久前,我正在处理类似的问题。要记住的一些重要事项:
因此,如果这不是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 App和Technical Note TN2277:Networking and Multitasking
使用此代码可使您的应用在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()
}
我希望您能通过此帮助获得成功