在我當前的應用程序中,我需要每小時通過TCP連接輪詢到服務器。我知道,最好的選擇之一是從服務器端使用推送通知,但我不能這樣做。所以目前我正在使用一個計時器,每9分鐘啓動一次,以保持應用程序在後臺運行。這工作正常..在小時我調查投票到服務器。每小時輪詢TCP服務器ios
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");
}
}
空間可用被調用,但沒有進一步從服務器..
只有音樂,位置或IP語音,允許在後臺運行,你不能輪詢,除非應用程序正在運行。請注意,如果您註冊了這些後臺任務並執行其他操作,Apple會注意並拒絕您的應用。 – Jano 2013-04-10 00:11:49
Yeap thats algood謝謝Jano,該應用使用定位服務來保持應用在用於輪詢服務器的10秒鐘內保持活躍狀態。它還將GPS數據發送到服務器。希望蘋果能夠接受它足夠的相關性。否則推通知它是 – 2013-04-10 00:19:24