在我当前的应用程序中,我需要每小时通过 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");
}
}
可用空间被调用,但离服务器没有更远的地方..