多文件上传的一个进度条

时间:2016-04-14 06:39:47

标签: objective-c nsurlsessionuploadtask

我尝试使用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张图片的进度?

1 个答案:

答案 0 :(得分:1)

最好的方法是使用NSProgress,它允许您将子NSProgress个更新汇总成一个。

  1. 因此,请定义父NSProgress

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

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

    使用observedProgress的{​​{1}},更新NSProgressView时,相应的NSProgress也会自动更新。

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

    NSProgress

    self.child1Progress = [NSProgress progressWithTotalUnitCount:totalBytes1 parent:self.parentProgress pendingUnitCount:1];
    
  4. 然后,当各个网络请求继续时,请使用到目前为止的总字节数更新各自的self.child2Progress = [NSProgress progressWithTotalUnitCount:totalBytes2 parent:self.parentProgress pendingUnitCount:1];

    NSProgress
  5. 更新单个子self.child1Progress.completedUnitCount = countBytesThusFar1; 个对象的completedUnitCount将自动更新父NSProgress个对象的fractionCompleted,因为您正在观察,将相应地更新您的进度视图。

    只需确保父级的NSProgress等于子级totalUnitCount的总和。

相关问题