title: Average progress of all the NSURLSessionTasks in a NSURLSession
body: <p>An <code>NSURLSession</code> will allow you to add to it a large number of <code>NSURLSessionTask</code> to download in the background. </p>
  
  <p>If you want to check the progress of a single <code>NSURLSessionTask</code>, it’s as easy as</p>
  
  <p><code>double taskProgress = (double)task.countOfBytesReceived / (double)task.countOfBytesExpectedToReceive;</code></p>
  
  <p>But what is the best way to check <strong>the average progress of all the <code>NSURLSessionTasks</code> in a <code>NSURLSession</code></strong>? </p>
  
  <p>I thought I’d try averaging the progress of all tasks:</p>
  
  <pre><code>[[self backgroundSession] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *allDownloadTasks) {
  
      double totalProgress = 0.0;
  
      for (NSURLSessionDownloadTask *task in allDownloadTasks) {
  
          double taskProgress = (double)task.countOfBytesReceived / (double)task.countOfBytesExpectedToReceive;
  
          if (task.countOfBytesExpectedToReceive &gt; 0) {
              totalProgress = totalProgress + taskProgress;
          }
          NSLog(@"task %d: %.0f/%.0f - %.2f%%", task.taskIdentifier, (double)task.countOfBytesReceived, (double)task.countOfBytesExpectedToReceive, taskProgress*100);
      }
  
      double averageProgress = totalProgress / (double)allDownloadTasks.count;
  
      NSLog(@"total progress: %.2f, average progress: %f", totalProgress, averageProgress);
      NSLog(@" ");
  
  }];
  </code></pre>
  
  <p>But the logic here is wrong: Suppose you have 50 tasks expecting to download 1MB and 3 tasks expecting to download 100MB. If the 50 small tasks complete before the 3 large tasks, <code>averageProgress</code> will be much higher than the actual average progress. </p>
  
  <p>So you have to calculate average progress according to the <strong>TOTAL</strong> <code>countOfBytesReceived</code> divided by the <strong>TOTAL</strong> <code>countOfBytesExpectedToReceive</code>. But the problem is that a <code>NSURLSessionTask</code> figures out those values <em>only once it starts</em>, and it might not start until another task finishes. </p>
  
  <p>So how do you check <strong>the average progress of all the <code>NSURLSessionTasks</code> in a <code>NSURLSession</code></strong>? </p>