One progress bar for multiple file upload
Asked Answered
U

1

1

I'm trying to upload 2 images(one at a time)using NSURLSessionTask.

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
   didSendBodyData:(int64_t)bytesSent
    totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
if (self.imageName1 != nil && self.imageName2 != nil) 
    {
        float progress = (float)totalBytesSent / (float)totalBytesExpectedToSend;
        if (progress != 1.00)
        {
            // Calculate total bytes to be uploaded or the split the progress bar in 2 halves
        }
    }
    else if (self.imageName1 != nil && self.imageName2 == nil)
    {
        float progress = (float)totalBytesSent / (float)totalBytesExpectedToSend;
        if (progress != 1.00)
        [self.progressBar1 setProgress:progress animated:YES];
    }
    else if (self.imageName2 != nil && self.imageName1 == nil)
    {
        float progress = (float)totalBytesSent / (float)totalBytesExpectedToSend;
        if (progress != 1.00)
        [self.progressBar2 setProgress:progress animated:YES];  
    }
}

How can I use a single progress bar to show the progress in case of 2 image uploads ?

Unearned answered 14/4, 2016 at 6:39 Comment(0)
S
1

The best way is to use NSProgress which allows you to roll-up child NSProgress updates into one.

  1. So define a parent NSProgress:

    @property (nonatomic, strong) NSProgress *parentProgress;
    
  2. Create the NSProgress and tell the NSProgressView to observe it:

    self.parentProgress = [NSProgress progressWithTotalUnitCount:2];
    self.parentProgressView.observedProgress = self.parentProgress;
    

    By using observedProgress of the NSProgressView, when the NSProgress is updated, the corresponding NSProgressView will automatically be updated, too.

  3. Then, for the individual requests, create individual child NSProgress entries that will be updated, e.g.:

    self.child1Progress = [NSProgress progressWithTotalUnitCount:totalBytes1 parent:self.parentProgress pendingUnitCount:1];
    

    and

    self.child2Progress = [NSProgress progressWithTotalUnitCount:totalBytes2 parent:self.parentProgress pendingUnitCount:1];
    
  4. Then, as the individual network requests proceed, update their respective NSProgress with the total bytes thus far:

    self.child1Progress.completedUnitCount = countBytesThusFar1;
    

The updating of the completedUnitCount of the individual child NSProgress objects will automatically update the fractionCompleted of the parent NSProgress object, which, because you're observing that, will update your progress view accordingly.

Just make sure that the totalUnitCount for the parent to be equal to the sum of the pendingUnitCount of the children.

Superaltar answered 14/4, 2016 at 7:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.