6

I am using NSURLSession + NSURLDownloadTask with completionHandler:

[session downloadTaskWithURL:downloadURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error)

it works nice.

But when I want to track download in a progressBar I am running into problems. I am trying to use NSURLSessionDownloadDelegate to track loading. With the upper completionHandler it is never called?!

Using:

 NSURLSessionDownloadTask *downloadTask =
[session downloadTaskWithURL:downloadURL];

will call the delegates.

Is there any way to use completionHandler AND delegates?
Or any other way to track download while using completionHandler?

Yedy
  • 2,107
  • 1
  • 25
  • 30

2 Answers2

2

To employ the didWriteData method of the NSURLSessionDownloadDelegate, you sadly have to use the rendition of downloadTaskWithURL without the completionHandler and then implement your own URLSession:downloadTask:didFinishDownloadingToURL: to perform those actions you otherwise would have done in the completion handler.

This is a little annoying (especially since the NSURLSessionDownloadDelegate is set at the session object), but it's how it works.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
2

From the documentation:

NSURLSession returns data in one of two ways, depending on the methods you call:

  • To a completion handler block that returns data to your app when a transfer finishes successfully or with an error.
  • By calling methods on your custom delegate as the data is received.

One of two ways. Either use the completion handler (if all you want is to be notified at the end) or use the delegate methods (if you want full information as you go). Not a problem. It's not like the delegate methods are hard to use or anything; it's probably just about always better to use them.

matt
  • 515,959
  • 87
  • 875
  • 1,141