7

iOS

Can we call the method after the application has been minimized?

For example, 5 seconds after was called applicationDidEnterBackground:.

I use this code, but test method don't call

- (void)test
{
    printf("Test called!");
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self performSelector:@selector(test) withObject:nil afterDelay:5.0];
}
Rubinc
  • 125
  • 6
  • your methods in **AppDelegate.m file** `applicationWillResignActive` and then `applicationDidEnterBackground` is called. – Rohan Jul 11 '13 at 10:05
  • Thank you. But I mean, when it is in the background – Rubinc Jul 11 '13 at 10:07
  • Have a look at [How can I take a screenshot of the iPhone home screen programmatically](http://stackoverflow.com/q/13459682/593709) – Adil Soomro Jul 11 '13 at 10:18
  • 1
    I advise to read it: http://stackoverflow.com/questions/10319643/objective-c-proper-use-of-beginbackgroundtaskwithexpirationhandler – stosha Jul 11 '13 at 10:20

1 Answers1

7

You can use the background task APIs to call a method after you've been backgrounded (as long as your task doesn't take too long - usually ~10 mins is the max allowed time).

iOS doesn't let timers fire when the app is backgrounded, so I've found that dispatching a background thread before the app is backgrounded, then putting that thread to sleep, has the same effect as a timer.

Put the following code in your app delegate's - (void)applicationWillResignActive:(UIApplication *)application method:

// Dispatch to a background queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

    // Tell the system that you want to start a background task
    UIBackgroundTaskIdentifier taskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        // Cleanup before system kills the app
    }];

    // Sleep the block for 5 seconds
    [NSThread sleepForTimeInterval:5.0];

    // Call the method if the app is backgrounded (and not just inactive)
    if (application.applicationState == UIApplicationStateBackground)
        [self performSelector:@selector(test)];  // Or, you could just call [self test]; here

    // Tell the system that the task has ended.
    if (taskID != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:taskID];
    }

});
Vinny Coyne
  • 2,365
  • 15
  • 24