文件下载器使用NSURLSessionTask downloadTask

时间:2017-05-15 10:20:29

标签: ios objective-c iphone xcode nsurlsessiontask

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

我尝试下面的代码成功下载多个文件...但无法添加进度条请帮忙 enter image description here

enter image description here

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

我得到swift code: 有人可以为objective-C

创建或提供解决方案

1 个答案:

答案 0 :(得分: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;
}