Reputation: 51
I'm starting to implement a download method using NSURLSession and successfully downloaded different files from multiple request. But now I wanted to add a progress track, however the delegates for download progress is not being triggered.
Here is my code:
NSURLSessionConfiguration *defaultConfigObject = NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate:self delegateQueue:nil];
NSURLSessionDownloadTask * downloadTask = [defaultSession downloadTaskWithRequest:request completionHandler:^(NSURL * __nullable location,
NSURLResponse * __nullable response, NSError * __nullable error) {
NSData *data = [NSData dataWithContentsOfURL:location];
[[NSFileManager defaultManager] createFileAtPath:docPath contents:data attributes:nil];
if ([[NSFileManager defaultManager] fileExistsAtPath:docPath]) {
NSDictionary *notificationDic = [[NSDictionary alloc] initWithObjectsAndKeys:docPath,@"docPath", item, @"item", nil];
[[NSNotificationCenter defaultCenter] postNotificationName: @"openFile" object:nil userInfo:notificationDic];
}
}];
[downloadTask resume];
I have the NSURLSessionDownloadDelegate on my header file.
I needed to use completion handler to be able to perform different tasks with the file.
Is there a way I can do it?
Upvotes: 1
Views: 1998
Reputation: 377
In my case the problem was I conform my class with URLSessionDelegate
instead of URLSessionDownloadDelegate
. Even if I was implementing the URLSessionDownloadDelegate
methods.
Upvotes: 0
Reputation: 2142
You will have to initiate your download with:
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;
And implement the delegate method for your progress:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;
And since you need to perform various tasks when finished, you should also implement this delegate method:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location;
Essentially, the completion handler routines are "convenience" routines to quickly perform the task and then when finished, perform the completion handler. But they don't call the other delegate routines.
Upvotes: 1
Reputation: 437422
If you use downloadTaskWithRequest
rendition without the completionHandler
parameter, then the progress delegate methods will be called. Obviously, you'll have to move the code currently in the completionHandler
block into the didFinishDownloadingToURL
method. But if you do this, you'll see didWriteData
called.
Upvotes: 3