1

I'm trying to keep the App running on task in background even if the User minimized and started working in other stuff on the ios device, but my method is hit only when the App is active on the screen. Am I missing something obvious here?

-(void) viewDidAppear:(BOOL)animated
{
  [self performSelectorInBackground:@selector(RunMethodEvenWhenMinimized) withObject:nil];
}

-(void)RunMethodEvenWhenMinimized
{
    while(YES)
    {
        //My Code
        sleep(10);
    }
}
RollRoll
  • 8,133
  • 20
  • 76
  • 135

1 Answers1

3

The problem is that you seem to be confusing background processing, and NSObject's background thread helper function. You aren't actually specifying that your method should run in the background, rather, that it will run on a thread that isn't the main thread. It's recommended that you use -[UIApplication beginBackgroundTaskWithExpirationHandler:]; to notify the system that your application needs to exceed it's allotted time in the foreground for method execution. Your code will end up looking something like this when all is said and done:

-(void) viewDidAppear:(BOOL)animated
{
    UIApplication *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    bgTask = UIBackgroundTaskInvalid;
}];
    [self RunMethodEvenWhenMinimized];
    [app endBackgroundTask:bgTask];
}

-(void)RunMethodEvenWhenMinimized
{
    while(YES)
    {
        //My Code
        sleep(10);
    }
}
CodaFi
  • 43,043
  • 8
  • 107
  • 153