NSURLSession download task failing after it already succeeded - ios

I am experiencing a strange issue from time to with my NSURLSessionDownloadTasks (using a background download configuration).
It is always related to errors with NSURLDomain code NSURLErrorBackgroundSessionWasDisconnected (-997). The error itself usually seems to be coming from the app generically crashing or being forcefully closed during development from Xcode.
The relevant code boils down to
- (void)download:(NSURLRequest *)request
{
NSURLSessionDownloadTask *downloadTask = [self.urlSession downloadTaskWithRequest:request];
[downloadTask resume];
}
- (void) URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)tempLocation
{
NSLog(#"task %# didFinishDownloadingToURL with status code %#", downloadTask, #([downloadTask.response statusCode]));
}
- (void) URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
NSLog(#"task %# didCompleteWithError %#", task, error);
}
The problem in these cases is, that the same NSURLSessionDownloadTask gets two (instead of only one expected) call in -[NSURLSessionTaskDelegate URLSession:task:didCompleteWithError:]. Once without an error (which aligns to a call with a 200 OK response code to -[NSURLSessionDownloadDelegate URLSession:downloadTask:didFinishDownloadingToURL:]) and then another time, usually a couple seconds later with an error (-997). Both times it's exactly the same memory address for the task being passed into these delegate methods.
Has anybody else experienced something similar? I am not expecting that second callback after I was already told that my task succeeded. Is there any obvious reason why the NSURLSession may still hold on to a task it reportedly finished already but then all of a sudden thinks it should inform me that it's lost connectivity to it background transfer service?

FWIW, I had a similar issue because I was updating the UI from the NSURLSession delegate methods, which run in background thread.
So, the solution for me was to move the UI-related code to run on the main thread as below:
dispatch_async(dispatch_get_main_queue(), ^{
//code updating the UI.
});

Related

NSURLSession delegate didCompleteWithError not called

I have the below implementation of NSURLSession .
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
self.session = [NSURLSession sessionWithConfiguration:configuration
delegate:self
delegateQueue: nil];
NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request];
[task resume];
while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:100000]];
}
and i have implemented the below delegate methds:
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)aresponse
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didCompleteWithError:(NSError *)error
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
NSURLCredential *credential))completionHandler
the "finished" variable for while loop above is set to 1 when didCompleteWithError delegate is received when indicates that there is some issue like network down, etc...
When network is down, i don't get didCompleteWithErrorcallback , hence the while loop does not exit even though 10sec timeout has been specified and my app crashes giving Memory warning.
I do properly receive didReceiveData, didReceiveResponse callback in all scenarious .have not checked didReceiveChallenge callback though as it requires HTTPs setup here.
so , i have following questions to ask , if you can help me :
1)Why is didCompleteWithError callback not received when network is down?
2)Considering no network issues ,is didCompleteWithError callback received on successful completion of task ?If no, what callback would indicate the completion of task , like connectionDidFinishLoading when using NSURLConnection ?
I have used cachepolicy in the request parameter while starting task. Is it because of this that didcompletewitherror is not called n instead caching delegate should be implemented??
Guys, Please help. I am stuck.
Thankyou
delegateQueue :[NSOperationQueue mainQueue]
instead of instead of delegateQueue :nil did the trick .
I am still not sure how. But yes, the issue is gone.
could anybody explain how this worked ?
Your loop "while(!finished)" is really bad practice. Basically the download task is async operation however with your while-loop you are blocking the thread and force the download task to finish in that thread. This might impact system behavior.
I belive removing this loop will solve your problem.

Background Upload With Stream Request Using NSUrlSession in iOS8

Previously in iOS7 when we try to upload with stream request in background we get following exception
Terminating app due to uncaught exception 'NSGenericException', reason: 'Upload tasks in background sessions must be from a file'
But in iOS8 there is no exception when we try to upload with stream in background.
Now my question is
1) Is backgourd upload with uploadTaskWithStreamedRequest: allowed in iOS8?
2) In iOS8 i am using background NSURLConfiguration with uploadTaskWithStreamedRequest. I am using -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *))completionHandler to provide stream to NSUrlSession. When app is in foreground it is working fine and uploading my file to the server. But as soon as the app igoes in background the stream ends and NSURLSession completes with following error
Error Domain=NSURLErrorDomain Code=-997 "Lost connection to background transfer service"
I think when app goes in background my stream ends. Now my question is that in which runloop should I should I schedule my Stream or let me know if there is any mistake in my understanding.
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *))completionHandler
{
// Open producer/consumer streams. We open the producerStream straight
// away. We leave the consumerStream alone; NSURLConnection will deal
// with it.
NSLog(#"%#", [NSThread currentThread]);
NSInputStream *consStream;
NSOutputStream *prodStream;
[NSStream createBoundInputStream:&consStream outputStream:&prodStream bufferSize:SFAMaxBufferLength];
assert(consStream != nil);
assert(prodStream != nil);
self.consumerStream = consStream;
self.producerStream = prodStream;
self.producerStream.delegate = self;
[self.producerStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[self.producerStream open];
// Set up our state to send the body prefix first.
self.buffer = [self.bodyPrefixData bytes];
self.bufferLimit = [self.bodyPrefixData length];
completionHandler(self.consumerStream);
}
You can't upload streamed tasks using Background Configuration. I successfully upload data only in two cases:
Download task with data stored in request body.
Upload task from file. In that case you will not receive response body.
You can upload a multipart file in background - just that this is not straight forward. Refer: AFNetworking error in uploadTaskWithStreamedRequest

NSURLDomainErrorDomain error -999 when app terminate with NSURLSession

I have big trouble with NSURLSession when i'll terminate the App.
I have downloaded the apple sample:
https://developer.apple.com/library/ios/samplecode/SimpleBackgroundTransfer/Introduction/Intro.html
on Apple reference.
When i start download the file download correctly.
When i enter in background the download continues to.
When i terminate the application and i restart the app the application enter in:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
And i catch this error:
The operation couldn't be completed. (NSURLErrorDomain error -999.)
It seems that i cannot restore download when app has been terminated. It's correct?For proceed with download i must leave application active in background?
Thank you
Andrea
A couple of observations:
Error -999 is kCFURLErrorCancelled.
If you are using NSURLSessionDownloadTask, you can download those in the background using background session configuration, e.g.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:kBackgroundIdentifier];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
If not using background session (e.g. you have to use data task, for example), you can use beginBackgroundTaskWithExpirationHandler to request a little time for the app the finish requests in the background before the app terminates.
Note, when using background sessions, your app delegate must respond to handleEventsForBackgroundURLSession, capturing the completion handler that it will call when appropriate (e.g., generally in URLSessionDidFinishEventsForBackgroundURLSession).
How did you "terminate the app"? If you manually kill it (by double tapping on home button, holding down on icon for running app, and then hitting the little red "x"), that will not only terminate the app, but it will stop background sessions, too. Alternatively, if the app crashes or if it is simply jettisoned because foreground apps needed more memory, the background session will continue.
Personally, whenever I want to test background operation after app terminates, I have code in my app to crash (deference nil pointer, like Apple did in their WWDC video introduction to NSURLSession). Clearly you'd never do that in a production app, but it's hard to simulate the app being jettisoned due to memory constraints, so deliberately crashing is a fine proxy for that scenario.
i insert this new lines of code:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
BLog();
NSInteger errorReasonNum = [[error.userInfo objectForKey:#"NSURLErrorBackgroundTaskCancelledReasonKey"] integerValue];
if([error.userInfo objectForKey:#"NSURLErrorBackgroundTaskCancelledReasonKey"] &&
(errorReasonNum == NSURLErrorCancelledReasonUserForceQuitApplication ||
errorReasonNum == NSURLErrorCancelledReasonBackgroundUpdatesDisabled))
{
NSData *resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
if (resumeData) {
// resume
NSURL *downloadURL = [NSURL URLWithString:DownloadURLString];
NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
if (!self.downloadTask) {
self.downloadTask = [self.session downloadTaskWithRequest:request];
}
[self.downloadTask resume];
if (!_session){
[[_session downloadTaskWithResumeData:resumeData]resume];
}
}
}
}
It catch NSURLErrorCancelledReasonUserForceQuitApplication but when the application try to [[_session downloadTaskWithResumeData:resumeData]resume]
reenter again in:
(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
and give me again -999 error.
I use this configuration
- (NSURLSession *)backgroundSession
{
/*
Using disptach_once here ensures that multiple background sessions with the same identifier are not created in this instance of the application. If you want to support multiple background sessions within a single process, you should create each session with its own identifier.
*/
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:#"com.example.apple-samplecode.SimpleBackgroundTransfer.BackgroundSession"];
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
});
return session;
}
let me explain what i mean with "terminate the app" (in ios8):
double tap on home button
swipe on my open app.
app disappear from open app list
relaunch app.
When i reopen the app i enter into callback with error
The operation couldn't be completed. (NSURLErrorDomain error -999.)
There is something that i can't understand. This behaviour make me crazy! :-(

NSURLSessionTask never calls back after timeout when using background configuration

I am using NSURLSessionDownloadTask with background sessions to achieve all my REST requests. This way I can use the same code without have to think about my application being in background or in foreground.
My back-end has been dead for a while, and I have taken that opportunity to test how does NSURLSession behave with timeouts.
To my utter surprise, none of my NSURLSessionTaskDelegate callbacks ever gets called. Whatever timeout I set on the NSURLRequest or on the NSURLSessionConfiguration, I never get any callback from iOS telling me that the request did finish with timeout.
That is, when I start a NSURLSessionDownloadTask on a background session. Same behavior happens the application is in background or foreground.
Sample code:
- (void)launchDownloadTaskOnBackgroundSession {
NSString *sessionIdentifier = #"com.mydomain.myapp.mySessionIdentifier";
NSURLSessionConfiguration *backgroundSessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:sessionIdentifier];
backgroundSessionConfiguration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
backgroundSessionConfiguration.timeoutIntervalForRequest = 40;
backgroundSessionConfiguration.timeoutIntervalForResource = 65;
NSURLSession *backgroundSession = [NSURLSession sessionWithConfiguration:backgroundSessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.timeout.com/"]];
request.timeoutInterval = 30;
NSURLSessionDownloadTask *task = [backgroundSession downloadTaskWithRequest:request];
[task resume];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(#"URLSession:task:didCompleteWithError: id=%d, error=%#", task.taskIdentifier, error);
}
However, when I use the default session, then I do get an error callback after 30seconds (the timeout that I set at request level).
Sample code:
- (void)launchDownloadTaskOnDefaultSession {
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
defaultSessionConfiguration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
defaultSessionConfiguration.timeoutIntervalForRequest = 40;
defaultSessionConfiguration.timeoutIntervalForResource = 65;
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.timeout.com/"]];
request.timeoutInterval = 30;
NSURLSessionDownloadTask *task = [defaultSession downloadTaskWithRequest:request];
[task resume];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(#"URLSession:task:didCompleteWithError: id=%d, error=%#", task.taskIdentifier, error);
}
I cannot seem to find in the documentation anything that suggests that the timeout should behave differently when using background sessions.
Has anyone bumped into that issue as well?
Is that a bug or a feature?
I am considering creating a bug report, but I usually get feedback much faster on SO (a few minutes) than on the bug reporter (six months).
Regards,
Since iOS8, the NSUrlSession in background mode does not call this delegate method if the server does not respond.
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
The download/upload remains idle indefinitely.
This delegate is called on iOS7 with an error when the server does not respond.
In general, an NSURLSession background session does not fail a task if
something goes wrong on the wire. Rather, it continues looking for a
good time to run the request and retries at that time. This continues
until the resource timeout expires (that is, the value of the
timeoutIntervalForResource property in the NSURLSessionConfiguration
object you use to create the session). The current default for that
value is one week!
Quoted information taken from this Source
In other words, the behaviour of failing for a timeout in iOS7 was incorrect. In the context of a background session, it is more interesting to not fail immediately because of network problems. So since iOS8, NSURLSession task continues even if it encounters timeouts and network loss. It continues however until timeoutIntervalForResource is reached.
So basically timeoutIntervalForRequest won't work in Background session but timeoutIntervalForResource will.
Timeout for DownloadTask is thrown by NSURLSessionTaskDelegate not NSURLSessionDownloadDelegate
To trigger a timeout(-1001) during a downloadTask:
Wait till download starts.
percentage chunks of data downloading will trigger:
URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:
Then PAUSE the whole app in XCode debugger.
Wait 30secs.
Unpause the app using XCode debugger buttons
The http connection from server should time out and trigger:
-1001 "The request timed out."
#pragma mark -
#pragma mark NSURLSessionTaskDelegate - timeouts caught here not in DownloadTask delegates
#pragma mark -
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
if(error){
ErrorLog(#"ERROR: [%s] error:%#", __PRETTY_FUNCTION__,error);
//-----------------------------------------------------------------------------------
//-1001 "The request timed out."
// ERROR: [-[SNWebServicesManager URLSession:task:didCompleteWithError:]] error:Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x1247c42e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://directory.clarksons.com/api/1/dataexport/ios/?lastUpdatedDate=01012014000000, NSErrorFailingURLKey=https://directory.clarksons.com/api/1/dataexport/ios/?lastUpdatedDate=01012014000000, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}
//-----------------------------------------------------------------------------------
}else{
NSLog(#"%s SESSION ENDED NO ERROR - other delegate methods should also be called so they will reset flags etc", __PRETTY_FUNCTION__);
}
}
There is one method in UIApplicationDelegate,which will let you know about background process.
-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
If there are more than one session ,you can identify your session by
if ([identifier isEqualToString:#"com.mydomain.myapp.mySessionIdentifier"])
One more method is used to periodically notify about the progress .Here you can check the state of NSURLSession
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
NSURLSessionTaskStateRunning = 0,
NSURLSessionTaskStateSuspended = 1,
NSURLSessionTaskStateCanceling = 2,
NSURLSessionTaskStateCompleted = 3,
Like you, the app I'm working on always uses a background session. One thing I noticed is that the timeout works properly if it's interrupting a working connection, i.e., the transfer started successfully. However, if I start a download task for a URL that doesn't exist, it wouldn't time out.
Given that you said your backend had been dead for awhile, this sounds a lot like what you were seeing.
It's pretty easy to reproduce. Just set a timeout for like 5 seconds. With a valid URL you'll get some progress updates and then see it timeout. Even with a background session. With an invalid URL it just goes quiet as soon as you call resume.
I have come up to the exact same problem. One solution that i have found is to use two sessions, one for foreground downloads using the default configuration and one for background downloads with background configuration. When changing to the background/foreground generate resume data and pass it from one to the other. But i am wondering if you have found another solution.

Handling NSURLSessionDownloadTask failure

Originially I thought that if a NSURLSessionDownloadTask finishes successfully URLSession:downloadTask:didFinishDownloadingToURL: method will get called, if it fails for some reason - URLSession:task:didCompleteWithError:.
It works as expected on simulator (only one of this method is called for one download task) but on device this is not the case: in case of failure both these methods are called, URLSession:downloadTask:didFinishDownloadingToURL: being the first the one. (an both these methods pass the same task in parameters)
Is there something I am missing?
I found a solution to this problem:
To get the status code in the response header, you must first start a NSURLSessionDataTask.
This will call the following delegate method URLSession:dataTask:didReceiveResponse:completionHandler:.
In this method, you can first check the status code of the NSURLResponse parameters (by casting it to a NSHTTPURLResponse) and finally call the completion handler with either NSURLSessionResponseBecomeDownload to convert your dataTask to a downloadTask (which will behave as you would expect from a NSURLSessionDownloadTask) or NSURLSessionResponseCancel to avoid downloading some data you don't need (for example if the response's status code is 404).
Also, if you need to do something with the converted NSURLSessionDownloadTask (like storing it in an array or a dictionary or replacing the data task with the new object), it can be done in the URLSession:dataTask:didBecomeDownloadTask:
Hope this helps someone!
According to Apple's documentation under NSURLSessionDownloadDelegate It is standard behavior.
/* Sent when a download task that has completed a download. The delegate should
* copy or move the file at the given location to a new location as it will be
* removed when the delegate message returns. URLSession:task:didCompleteWithError:
* will still be called. */
If you were doing a HTTP request, you can cast the task's response into a NSHTTPURLResponse to get the HTTP status code:
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL )location
{
NSLog(#"response is %d\n" ((NSHTTPURLResponse)downloadTask.response).statusCode);
NSLog(#"error is %#\n", [downloadTask.error localizedDescription]);
}
Apple's logic is that when you get a 404, error will still be null.
Use completion block instead of delegate:
NSURLSessionDownloadTask *mySessionDownloadTask = [myURLSession downloadTaskWithRequest:myRequest completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error)
{
dispatch_async(dispatch_get_main_queue(), ^{
if(!error)
{
// Finish loading
}
else
{
// Handle error
});
}];
Note: If you don't get the main queue, any update related to user interface will be retarded which causes unsuspected behaviors.
NSURLSessionDownloadTask is a subclass of NSURLSessionTask, which has an error property. Could you check that in your URLSession:downloadTask:didFinishDownloadingToURL: delegate method before you attempt to copy your file?

Resources