One progress bar for multiple file upload

天涯浪子 提交于 2019-12-11 10:54:02

问题


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 ?


回答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.



来源:https://stackoverflow.com/questions/36615525/one-progress-bar-for-multiple-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!