【问题标题】:One progress bar for multiple file upload多个文件上传的一个进度条
【发布时间】:2016-04-14 06:39:46
【问题描述】:

我正在尝试使用 NSURLSessionTask 上传 2 张图片(一次一张)。

- (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];  
    }
}

如果上传 2 张图片,如何使用单个进度条显示进度?

【问题讨论】:

    标签: objective-c nsurlsessionuploadtask


    【解决方案1】:

    最好的方法是使用NSProgress,它允许您将子NSProgress 更新合并为一个。

    1. 所以定义一个父NSProgress

      @property (nonatomic, strong) NSProgress *parentProgress;
      
    2. 创建NSProgress 并告诉NSProgressView 观察它:

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

      使用NSProgressView中的observedProgress,当NSProgress更新时,对应的NSProgressView也会自动更新。

    3. 然后,对于单个请求,创建将更新的单个子 NSProgress 条目,例如:

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

      self.child2Progress = [NSProgress progressWithTotalUnitCount:totalBytes2 parent:self.parentProgress pendingUnitCount:1];
      
    4. 然后,随着各个网络请求的进行,用迄今为止的总字节数更新它们各自的NSProgress

      self.child1Progress.completedUnitCount = countBytesThusFar1;
      

    更新单个子NSProgress 对象的completedUnitCount 将自动更新父NSProgress 对象的fractionCompleted,因为您正在观察,这将相应地更新您的进度视图。

    只要确保父级的totalUnitCount 等于子级的pendingUnitCount 的总和即可。

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 2012-07-17
      • 2015-10-19
      • 1970-01-01
      • 2011-10-07
      • 2016-11-16
      • 2011-12-07
      • 2017-12-07
      • 1970-01-01
      相关资源
      最近更新 更多