在我当前的应用程序中,我需要每小时通过 TCP 连接轮询一次服务器。我知道最好的选择之一是使用服务器端的推送通知,但我不能这样做。因此,目前我正在使用一个每 9 分钟触发一次的计时器,以保持应用程序在后台运行。这工作正常。在我向服务器调用民意调查的时间。
Tcp 连接已打开并生成轮询数据,但服务器没有响应。这是因为在后台应用程序无法运行需要几秒钟时间的代码块吗?任何帮助将不胜感激,我也会在下面发布一些代码,
if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
{
//Check if our iOS version supports multitasking I.E iOS 4
if ([[UIDevice currentDevice] isMultitaskingSupported])
{
//Check if device supports mulitasking
UIApplication *application = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard"
bundle: nil];
ViewController *controller = (ViewController*)[mainStoryboard
instantiateViewControllerWithIdentifier: @"viewController"];
[controller sendPoll];
});
}
}
然后写入输出数据的代码:
NSData *data = [[NSData alloc] initWithData:[string dataUsingEncoding:NSASCIIStringEncoding]];
[_cacheArray addObject:string];
[_outputStream write:[data bytes] maxLength:[data length]];
最后是streamDidReturn:
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
NSLog(@"event number %i ", eventCode);
switch (eventCode)
{
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (aStream == _inputStream)
{
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);
}
}
}
break;
case NSStreamEventErrorOccurred:
break;
case NSStreamEventEndEncountered:
break;
case NSStreamEventHasSpaceAvailable:
NSLog(@"space available");
break;
default:
NSLog(@"Unknown event");
}
}
可用空间被调用,但距离服务器没有进一步的空间。
我似乎找到了答案!
通过转移与服务器通信的功能,应用程序可以保持活动状态足够长的时间来发送和接收民意调查。唯一的问题似乎是从 appDelegate 访问另一个 ViewController 并期望它像在前台状态一样运行。
感谢您重新编辑问题,彻底清理了问题,所以谢谢,
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)