Reputation: 1265
I created a chat application using SocketRocket,when I quit the app(enter background mode) I want to receive the chat message! so i could do that by calling it a VoIP app but some people says Apple will reject it from the App Store unless it also truly does VoIP. So how can I do that and if the only way to do that is by calling it a VoIP app how does whatsapp handles this situation??
Here's what i did to keep the app alive in the background:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"Application entered background state.");
NSAssert(self.backgroundTask == UIBackgroundTaskInvalid, nil);
self.didShowDisconnectionWarning = NO;
self.backgroundTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Background task expired");
if (self.backgroundTimer)
{
[self.backgroundTimer invalidate];
self.backgroundTimer = nil;
}
[application endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
});
}];
dispatch_async(dispatch_get_main_queue(), ^{
self.backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(timerUpdate:) userInfo:nil repeats:YES];
});
}
- (void) timerUpdate:(NSTimer*)timer {
UIApplication *application = [UIApplication sharedApplication];
NSLog(@"Timer update, background time left: %f", application.backgroundTimeRemaining);
if ([application backgroundTimeRemaining] < 60 && !self.didShowDisconnectionWarning)
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif) {
localNotif.alertBody = @"Background session will expire in one minute.";
localNotif.alertAction = @"OK";
localNotif.soundName = UILocalNotificationDefaultSoundName;
[application presentLocalNotificationNow:localNotif];
}
self.didShowDisconnectionWarning = YES;
}
if ([application backgroundTimeRemaining] < 10)
{
// Clean up here
[self.backgroundTimer invalidate];
self.backgroundTimer = nil;
[application endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
}
}
Upvotes: 13
Views: 11800
Reputation: 3908
You can't keep alive your TCP socket in background , How I did achieve this feature whenever applicationDidEnterBackground called disconnect the socket and applicationDidBecomeActive Connect the socket so that server knows client socket is disconnect then save message to Offline Table . There was schedular on web server that runs periodically to send push notification. whenever user receive push notification and user taps on it you need to create a flow to launch the right conversation based on the parameter you gets in Remote notification dictionary.
Upvotes: 0
Reputation: 17710
I believe your only option is to use remote notifications. You need your app to register for them, and your server to detect when your app is not running (i.e. connected via the socket), and then send a notification instead.
Upvotes: 6