3

In my app I'm currently using an NSURLSessionDownloadTask to fetch a file via HTTP.

This class provides a useful delegate interface to monitor its progress and getting the bytes once the download completes via NSURLSessionDownloadDelegate, however I have not been able to find any way to access the bytes as they are downloaded (before the download completes).

Is accessing these bytes possible or do I need to download the file using some other mechanism?

Ivan
  • 2,314
  • 3
  • 18
  • 22

3 Answers3

2

If you want access to the bytes as they're downloaded, you should use data task, not download task. And if you then implement the NSURLSessionDataDelegate methods (specifically, didReceiveData), you can access the bytes, as they're downloaded.

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

You can use the following method to access the data as it is being received:

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
C6Silver
  • 3,127
  • 2
  • 21
  • 49
1

@C6Silver's answer is a method on the NSURLSessionDataDelegate, not NSURLSessionDownloadDelegate. Here's the method you need to implement:

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
      totalBytesWritten:(int64_t)totalBytesWritten
      totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;

You can use the totalBytesWritten parameter to access the data you require.

Edit - I misunderstood the question.

You are going to have to use an NSURLSessionDataTask rather than a DownloadTask, then use the delegate method on NSURLSessionDataDelegate:

- (void)URLSession:(NSURLSession *)session
      dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data;

This will allow you to access the data as it is received.

John Rogers
  • 2,192
  • 19
  • 29
  • I don't think that's true. From the apple documentation totalBytesWritten is "The total number of bytes transferred so far." I'm looking for the actual bytes written to the temp file or a pointer to this file. – Ivan Apr 28 '15 at 03:24
  • totalBytesWritten is... The total amount of bytes written to file, as it transfers the bytes straight to file or memory. The result is the same. – John Rogers Apr 28 '15 at 03:25
  • No. I want the contents of the bytes not the number of bytes received. – Ivan Apr 28 '15 at 03:27
  • 1
    I understand now. In that case, @C6Silver is correct. You will need to use an NSURLSessionDataTask to download the data, then use the method he posted in his answer to access the NSData object (the data received) as it is received. I've updated my answer. – John Rogers Apr 28 '15 at 03:31