I fire a bunch of downloads using NSURLSessionDownload
tasks and NSURLSession
with background configuration. Most of the time everything works fine but sometimes there is no temp file at the location
specified in the delegate
callback method. It happens on both simulator and device.
Here is the code, but everything looks pretty straight forward, just like they have it SimpleBackgroundTransfer sample.
....
for (NSUInteger i = 0; i < 10; i++) {
NSString *downloadURLString = ...;
NSURLSessionDownloadTask *task = [[self backgroundURLSession] downloadTaskWithURL:[NSURL URLWithString:downloadURLString]];
[task resume];
}
....
- (NSURLSession *)backgroundURLSession
{
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *identifier = @"com.yyy.backgroundTransfer";
NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration backgroundSessionConfiguration:identifier];
session = [NSURLSession sessionWithConfiguration:sessionConfig
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
});
return session;
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSLog(@"%s", __PRETTY_FUNCTION__);
NSAssert([[NSFileManager defaultManager] fileExistsAtPath:[location path]], nil);
/// This assert gets triggered every now and then. Any idea why?
/// And downloadTask.originalRequest in fact has a valid download URL and the status code for the response in downloadTask it is 200
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}
Also, the strange thing is that when this weird thing occurs no other NSURLSessionDelegate
methods are called, just URLSession:downloadTask:downloadTask:location
with no file at the location URL (and downloadTask.originalRequest
in fact has a valid download URL and the status code for the response in downloadTask it is 200).
If this weird thing happens it happens for all scheduled downloads, just like the system can not create files at all. URLSession:downloadTask:downloadTask:location
is called immediately.
Restarting device/simulator seems to always help. Relaunching the app never helps.
Did anyone experience anything like this?