1

我想创建文件下载管理器来下载多个文件,下载百分比具有播放暂停删除功能。

我尝试下面的代码成功下载多个文件...但无法添加进度条请帮助 在此处输入图像描述

在此处输入图像描述

for (int i = 0; i < [arr_bookChapter count]; i++) {
  NSURLSessionTask * downloadTask = [session downloadTaskWithURL: downloadfileUrl completionHandler: ^ (NSURL * location, NSURLResponse * response, NSError * error) {
      if (error == nil) {
          NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse * ) response;

          if ([httpResponse statusCode] == 200) {

              //download file save here                                                      

              dispatch_queue_t backgroundQueue = dispatch_queue_create("dispatch_queue_#1", 0);
              dispatch_async(backgroundQueue, ^ {

                  dispatch_async(dispatch_get_main_queue(), ^ {
                      // NSError *error;

                      //download complete here

                  });
              });
          }
      } else {
          //faile                                                  
      }

  }];
  [downloadTask resume];
}

在这里我得到了快速代码:有人可以为objective-C创建或提供解决方案吗

4

1 回答 1

1

你可以很容易地做到这一点,你只需要在你的 ViewContorller 中实现这些委托。

<NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate>

而且您需要遵循以下代码:

@property (nonatomic, retain) NSMutableData *dataToDownload;
@property (nonatomic) float downloadSize;

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];

    NSURL *url = [NSURL URLWithString: @"your url"];
    NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithURL: url];

    [dataTask resume];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    completionHandler(NSURLSessionResponseAllow);

    progressBar.progress=0.0f;
    _downloadSize=[response expectedContentLength];
    _dataToDownload=[[NSMutableData alloc]init];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    [_dataToDownload appendData:data];
    progressBar.progress=[ _dataToDownload length ]/_downloadSize;
}
于 2017-05-15T10:51:44.067 回答