在我目前的应用程序中,我需要每小时通过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");
}
}
可用空间被调用,但服务器没有进一步调用..
答案 0 :(得分:2)
通过转移与服务器通信的功能,应用程序保持活动状态足够长的时间来发送和接收轮询。唯一的问题似乎是从appDelegate访问另一个ViewController并期望它像在前台状态一样运行。
感谢您重新编辑问题,Defiantly清理了一下这个问题,谢谢,