Saturday, May 25, 2013

UIApplication setKeepAliveTimeout example in Objective C (iOS)


setKeepAliveTimeout: handler:

Configures a periodic handler for VoIP applications.
- (BOOL)setKeepAliveTimeout:(NSTimeInterval)timeout handler:(void (^)(void))keepAliveHandler
Parameters of [UIApplication setKeepAliveTimeout]
timeout
The maximum interval (measured in seconds) at which your application should be woken up to check its VoIP connection. The minimum acceptable timeout value is 600 seconds.
keepAliveHandler
A block that performs the tasks needed to maintain your VoIP network connection. Setting this parameter to nil releases the current handler block and prevents UIKit from scheduling the next wake.
Return Value
YES if the handler was installed or NO if it was not.
Discussion of [UIApplication setKeepAliveTimeout]
A voice-over-IP (VoIP) application can use this method to install a handler whose job is to maintain the application’s network connection with a VoIP server. This handler is guaranteed to be called before the specified timeout value but may be called at a slightly different time interval in order to better align execution of your handler with other system tasks, and thereby save power. Your handler has a maximum of 10 seconds to perform any needed tasks and exit. If it does not exit before time expires, the application is suspended.[UIApplication setKeepAliveTimeout]
Timeout values and handlers are not persisted between application launches. Therefore, if your application is terminated for any reason, you must reinstall the handler during the next launch cycle.
For calls to this method to succeed, the application must have the voip value in the array associated with the UIBackgroundModes key in its Info.plist file. Calling this method replaces the previously installed handler and timeout values, if any.
Example of [UIApplication setKeepAliveTimeout]
BOOL backgroundAccepted = [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{ [self backgroundHandler]; }];
 if (backgroundAccepted)
 {
      NSLog(@"VOIP backgrounding accepted");
 }
Example of [UIApplication setKeepAliveTimeout]
BOOL scheduled = [app setKeepAliveTimeout:pingTimeout handler:^{ // Schedule processing after some time interval      

  SchedulePing(0);
}
Example of [UIApplication setKeepAliveTimeout]
- (void)applicationDidEnterBackground:(UIApplication *)application {

    // This is where you can do your X Minutes, if >= 10Minutes is okay.
    BOOL backgroundAccepted = [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{ [self backgroundHandler]; }];
    if (backgroundAccepted)
    {
        NSLog(@"VOIP backgrounding accepted");
    }
}