Accessing bytes from NSURLSessionDownloadTask as they are downloaded
In my application, I am currently using NSURLSessionDownloadTask to fetch a file over HTTP.
This class provides a useful delegate interface for tracking its progress and retrieving bytes after the download is complete via NSURLSessionDownloadDelegate , however I have not been able to find any way to access the bytes as they are downloaded (before the download is complete).
Is it possible to access these bytes or do I need to download the file using some other mechanism?
If you need access to the bytes when loading them, you must use a data task, not a task load. And if you then implement the methods NSURLSessionDataDelegate
(specifically didReceiveData
), you can access the bytes as you load them.
You can use the following method to access data as it gets:
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
@ C6Silver's answer is a method in NSURLSessionDataDelegate , not NSURLSessionDownloadDelegate . Here's the way 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 a parameter totalBytesWritten
to access the data you want.
Edit . I didn't understand this question.
You will have to use NSURLSessionDataTask and not DownloadTask and then use the delegate method in NSURLSessionDataDelegate :
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data;
This will allow you to access the data as you receive it.