Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As you said, you need to balance <code>beginBackgroundTaskWithExpirationHandler</code> call with an <code>endBackgroundTask</code> call.</p> <p>One solution I have in mind looks like this:</p> <p>Create a new instance variable</p> <pre><code>UIBackgroundTaskIdentifier backgroundTaskID; </code></pre> <p>You are counting the requests anyway so you could also decrement getRequest in connectionDidFinishLoading:</p> <pre><code>- (void)connectionDidFinishLoading:(NSURLConnection *)connection { // process data from server getRequest--; if (getRequest == 0 &amp;&amp; backgroundTaskID != UIBackgroundTaskInvalid) { [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID]; backgroundTaskID = UIBackgroundTaskInvalid; } } </code></pre> <p>Now the background task gets ended after the last request has been completed. To start only one background task you start it in a method that gets called when the app goes to the background.</p> <p>You need to listen for the <code>UIApplicationDidEnterBackgroundNotification</code></p> <pre><code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil]; </code></pre> <p>and implement the method</p> <pre><code>- (void)applicationDidEnterBackground:(NSNotification *)notification { if (getRequest &gt; 0) { backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID]; backgroundTaskID = UIBackgroundTaskInvalid; }]; } } </code></pre> <p>Now you only have one running background task that starts automatically when your app goes to the background and you have running requests that gets ended when all your requests are done.</p> <p>Another improvement would be to add your network requests to an NSOperationQueue to avoid the manual counting and limit the number of concurrent requests.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload