URLSession didReceiveChallenge is too slow - ios

The execution of my app usually stops for 2-3 seconds (even 5 seconds) at didReceiveChallenge. Around 1 out of 10 times it takes forever.
The whole thing works, but what can I do to speed it up?
Here's my code:
- (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler{
NSLog(#"*** KBRequest.NSURLSessionDelegate - didReceiveChallenge IOS10");
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
if([challenge.protectionSpace.host isEqualToString:#"engine.my.server"]){
NSURLCredential *credential = [NSURLCredential credentialForTrust: challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
else{
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
}
}

You MUST call the completion handler EVERY time this method is called. You're only calling it for a single protection space.
When the OS calls this method on your delegate, the NSURLSession stack sits there dutifully waiting for you to call the completion handler block. If you fail to call the completion handler, your request will just sit in limbo until the request times out.
To fix this, at the bottom of the method, add:
} else {
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}

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.

NSURLSession download task failing after it already succeeded

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.
});

NSURLSessionTask authentication challenge completionHandler and NSURLAuthenticationChallenge client

I am implementing a custom NSURLProtocol, and internally want to use NSURLSession with data tasks for internal networking instead of NSURLConnection.
I have hit an interesting problem and wonder about the internal implementation of the challenge handler of NSURLSession/NSURLSessionTask.
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler;
Here I am basically provided with two different challenge handlers, one being the completionHandler block, which is provided with all necessary information to handle the challenge, but there is also the legacy NSURLAuthenticationChallenge.client which has methods that correspond pretty much one to one with the completionHandler information options.
Since I am developing a protocol, and would like to pass certain authentication challenges upward the URL loading system for the calling API to implement, I need to use the NSURLSession client method:
- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
My question is whether the internal implementation of the completionHandler and NSURLAuthenticationChallenge.client is the same, and if so, can I skip calling the completion handler in the delegate method, with expectance that the URL loading system will call the appropriate NSURLAuthenticationChallenge.client method?
To answer my own question, the answer is no. Moreover, Apple's provided challenge sender does not implement the entire NSURLAuthenticationChallengeSender protocol, thus crashing when client attempts to respond to challenge:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFURLSessionConnection performDefaultHandlingForAuthenticationChallenge:]: unrecognized selector sent to instance 0x7ff06d958410'
My solution was to create a wrapper:
#interface CPURLSessionChallengeSender : NSObject <NSURLAuthenticationChallengeSender>
- (instancetype)initWithSessionCompletionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler;
#end
#implementation CPURLSessionChallengeSender
{
void (^_sessionCompletionHandler)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential);
}
- (instancetype)initWithSessionCompletionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
self = [super init];
if(self)
{
_sessionCompletionHandler = [completionHandler copy];
}
return self;
}
- (void)useCredential:(NSURLCredential *)credential forAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
_sessionCompletionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}
- (void)continueWithoutCredentialForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
_sessionCompletionHandler(NSURLSessionAuthChallengeUseCredential, nil);
}
- (void)cancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
_sessionCompletionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
- (void)performDefaultHandlingForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
_sessionCompletionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
- (void)rejectProtectionSpaceAndContinueWithChallenge:(NSURLAuthenticationChallenge *)challenge
{
_sessionCompletionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil);
}
#end
And I replace the challenge object with a new one, using my wrapped sender:
NSURLAuthenticationChallenge* challengeWrapper = [[NSURLAuthenticationChallenge alloc] initWithAuthenticationChallenge:challenge sender:[[CPURLSessionChallengeSender alloc] initWithSessionCompletionHandler:completionHandler]];
[self.client URLProtocol:self didReceiveAuthenticationChallenge:challengeWrapper];

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.

defunct NSURLConnection never executes or times out

I'm running a LOT of asynchronous (delegate, not block) NSURLConnections simultaneously, and they all come back very quickly as I'm hitting a LAN server.
Every so often, one NSURLConnection will go defunct and never return.
connection:willSendRequest: is called but connection:didReceiveResponse: (and failure) is not.
Any ideas? I'm wondering if I should make a simple drop-in replacement using CFNetwork instead.
Edit: There's really not much code to show. What I've done is created a wrapper class to download files. I will note that the problem happens less when I run the connection on a separate queue - but still happens.
The general gist of what I'm doing is creating a download request for each cell as a tableview scrolls (in cellForRowAtIndexPath) and then asynchronously loading in an image file to the table cell if the cell is still visible.
_request = [NSMutableURLRequest requestWithURL:_URL];
_request.cachePolicy = NSURLRequestReloadIgnoringCacheData;
_request.timeoutInterval = _timeoutInterval;
if(_lastModifiedDate) {
[_request setValue:[_lastModifiedDate RFC1123String] forHTTPHeaderField:#"If-Modified-Since"];
}
_connection = [[NSURLConnection alloc] initWithRequest:_request
delegate:self
startImmediately:NO];
[_connection start];
As requested, instance variables:
NSMutableURLRequest *_request;
NSURLConnection *_connection;
And delegate methods:
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response {
NSLog(#"%# send", _URL);
return request;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"%# response", _URL);
_response = (id)response;
// create output stream
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
_receivedLength += data.length;
_estimatedProgress = (Float32)_receivedLength / (Float32)_response.expectedContentLength;
[_outputStream write:data.bytes maxLength:data.length];
// notify delegate
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// close output stream
// notify delegate
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"%# failure", _URL);
// notify delegate
}
- (void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if(_credential && challenge.previousFailureCount == 0) {
[[challenge sender] useCredential:_credential forAuthenticationChallenge:challenge];
}
}
After poking around in profiler, I found a lead, and it gave me a hunch.
My credentials were failing (not sure why...) and so previousFailureCount was not 0, and hence I wasn't using my credential object.
Changed the code to this and I have no problems:
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if(_credential) {
[[challenge sender] useCredential:_credential forAuthenticationChallenge:challenge];
}
}
A NSURLConnection will send either didReceiveResponse or didFailWithError.
Often, you're dealing with timeouts before didFailWithError occurs.

Resources