0

I have a Requirement where I need to Create and Start a thread when application enters the Background State. The function of the Created Thread is to fetch data from local DB and upload to server, and I don't need to do any updates on UI. My questions are:

  1. Where exactly should I create the Thread - either in applicationWillResignActive method or in applicationDidEnterBackground?
  2. Which is best way of creating the Thread - way or GCD or Posix Way?

The things I've tried

  1. I've already worked on Android so I know how can I achieve this scenario, but I'm new to iOS, so I'm getting bit confused to start with.
  2. I just tried the with NSThread concept, but it was not working. Below is code that I wrote to the best of my knowledge:

    - (void)applicationWillResignActive:(UIApplication *)application {
         [NSThread detachNewThreadSelector:@selector(FetchReportFromDBAndUpload) toTarget:self withObject:nil];
    }
    
    - (void)FetchReportFromDBAndUpload {
         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
         //Check for internet connection and fetch data from DB and upload to server
         [pool release];
    }
    

Is this correct way of creating the thread, or do I need to do some changes? If not please guide me how to achieve this. Thanks in advance

Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
RockandRoll
  • 409
  • 5
  • 23

1 Answers1

1

You must call the beginBackgroundTaskWithExpirationHandler: method of the UIApplication class from the AppDelegate's applicationDidEnterBackground: method. This method marks your task as a background task so the system will not kill it when the app enters background state. (Note that background tasks that are not related to VoiceIP, playing music, GPS tracking are still limited to more or less 10 minutes of background execution time, ie. they don't run forever.)

Here's more detailed information and a code example: http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html

Daniel Martín
  • 7,815
  • 1
  • 29
  • 34
  • Thanks Daniel, Can you explain me a bit more? can you just give me a code snippet of that ? – RockandRoll Mar 02 '13 at 13:21
  • @SunilHavnur You need to call `beginBackgroundTaskWithExpirationHandler:` from the `applicationDidEnterBackground:` method just before dispatching your long-running task. See listing 3-3 from the article I linked to. – Daniel Martín Mar 02 '13 at 13:28