Reputation: 1162
In my current application I am needed to poll to a server via TCP connection every hour. I am aware that one of the best options is to use Push Notifications from server side but I cant do that. So currently I am using a timer which fires every 9 minutes to keep the app running in the background. This works fine.. On the hour I call the Poll to the server.
The Tcp connection is opened and the poll data is generated however there is no response from the server. Is this because when in the background the app cannot run blocks of code that require a few seconds of time? Any help would be greatly appreciated, Ill post some code below too,
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];
});
}
}
Then the code to write the output data:
NSData *data = [[NSData alloc] initWithData:[string dataUsingEncoding:NSASCIIStringEncoding]];
[_cacheArray addObject:string];
[_outputStream write:[data bytes] maxLength:[data length]];
And finally the 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");
}
}
Space available gets called but nothing further from the server..
Upvotes: 3
Views: 807
Reputation: 1162
I seem to have found the answer!
By shifting my functions that communicate with the Server the app stays in an active state long enough to send and receive the poll's. The only issue seemed to be accessing another ViewController from the appDelegate and expecting it to run as if in a foreground state.
Thanks for the re-edit of the question, Defiantly cleaned up the question a bit so thanks,
Upvotes: 2