2

It seems that when you enqueue too many tasks (say, hundreds) on a background NSURLSession, it doesn't work well. How can you keep the number of enqueued tasks at a small fixed number, say 10?

Clay Bridges
  • 11,602
  • 10
  • 68
  • 118

1 Answers1

4

In the class that is responsible for enqueueing tasks, have a ivar to track the active tasks, e.g.

// In MySessionWrapper.m

@interface MySessionWrapper () {
    NSMutableSet *activeTaskIds;
}
@end

When you enqueue a task, you add its ID to that set:

[activeTaskIds addObject:@([task taskIdentifier])]

When you get a didComplete callback, you remove the ID, and if the number of active tasks falls below your target, you add more tasks:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    // other stuff
    [activeTaskIds removeObject:@([task taskIdentifier])]

    if ([activeTaskIds count] < NUMBER) {
        // add more tasks
    }
}

This system is working for me now.

Clay Bridges
  • 11,602
  • 10
  • 68
  • 118
  • Clay bridges Do i need to add this piece in didComplete __block UIBackgroundTaskIdentifier background_task; background_task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^ { [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; – Xcoder Aug 13 '14 at 20:47
  • @Xcoder Close. You should _totally_ ask that in a SO question, and I can give you a fuller answer. They format more nicely too. :) – Clay Bridges Aug 13 '14 at 21:52
  • Clay Bridges.. I will do that. I am in some difficulty now- I have been following several of your posts about NSURLSession managing uploads. Can we have a chat? – Xcoder Aug 13 '14 at 22:14
  • @Clay Do you think long running background tasks interfere with the lifecycle of NSURLSession? I am having a doubt - if a i create a bgtask and dont end it then the application method for handling background session events may never get called. – Xcoder Aug 13 '14 at 23:41
  • @clay heres my question http://stackoverflow.com/questions/25311736/unable-to-sustain-the-upload-of-files-in-the-background-with-nsurlsession – Xcoder Aug 14 '14 at 15:21
  • Hi, is there some github sample of this? I am new and trying to resolve a multi file upload, this is my SO question https://stackoverflow.com/questions/28483329/ios-8-multi-file-upload-nsurlsessionuploadtask – Huang Feb 14 '15 at 04:32
  • @Huang I personally don't have anything up right. The code I have is both proprietary and deeply intertwined with our product. – Clay Bridges Feb 16 '15 at 18:49
  • @ClayBridges I understand, question : I assume that all background work is asynchronous, should there by a mutex surrounding the logic in remove and adding active tasks? – Huang Feb 16 '15 at 20:00