Check if the current Session has expired in ASIHTTPREQUEST - ios

How can i check if the session that i have created using following code
NSURL *myWebserverURL = [NSURL URLWithString:XMLURLAddress];
ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:myWebserverURL];
[request setTimeOutSeconds:3600];
has expired? My scenario is that when my session is created and if the wifi is turned on and after a minute or two wifi is activated again, the session is expired. So how can i know that this session has expired?

First of all: ASIHTTPRequest is dead. If you're looking for something similar use AFNetworking, or check iOS7 brand new NSURLSession.
But for ASIHTTPRequest: Did you set the following completion blocks?
- (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock;
- (void)setFailedBlock:(ASIBasicBlock)aFailedBlock;
Another thing what might help you is adding any Reachability implementation to your project, so you can monitor the current connection type.

Related

NSURLSession restart the request

I am using the NSURLsession for network calls. I need to store the details to perform the restart on network error or manually when user performs the sync from app.
Do I need to store the NSURLsession object or NSURLSessionDataTask or taskIdentifier to achieve this?
I need to initiate the restart from some other class.
Help appreciated
NSURLSession is the task, an instance of NSURLSessionTask. Three type
data tasks
upload tasks
download tasks.
You can cancel , resume these task at any point if your session still validate. If your session invalidate, You need to call that code again which start this flow.
You can see here NSURLSession

NSURLConnection randomly fails until device reboot

I have been struggling with an issue where NSURLConnection calls instantly fail. The device needs to be rebooted entirely or Flight Mode needs to be toggled on/off to resolve the problem. Restarting the app (swipe up) alone does not help.
Some facts:
-All URLs are HTTPS, TLS 1.2 compatible with Forward Secrecy. There are no issues with ATS and iOS 9. The error has been present since iOS 7 and remains on 9.2.
-No third party frameworks are used by the app. I use only native NSURLConnection calls that always work, except for when this odd situation occurs.
-No infrastructure/network issues - other devices on same networks (same WiFi for instance) work in the same app at the same time. Going to/from 3G/Wifi makes no difference.
-I always implement willCacheResponse to return nil.
-The service is hosted on AWS Elastic Beanstalk, so some suggested that it might be a DNS caching issue in case of IP address changes - this seems unlikely to me and should trigger multiple errors at once on different devices, which I have never seen.
-The method called is didFailWithError, instantaneously, as if there were no Internet connection on the device at all - all other apps work, however.
-The website that hosts the API used by the app can be browsed with no problems at all times. The website actually makes the same requests to fetch data.
The error code returned is -1003, kCFURLErrorCannotFindHost. I've been following a thread on Git dealing with the same issue to no avail. https://github.com/AFNetworking/AFNetworking/issues/967
I tried using NSURLRequestReloadIgnoringCacheData for all my requests, but that did not help.
With this information, will anyone care to venture a guess what I might be doing wrong? I added the bounty because I have no idea how to approach this problem - especially because it's so inconsistent. And it is definitely not a legitimate error (that is, that the domain could not be found), as the service is operating fine while this happens on random clients.
I create my request with a static method that looks like this. It's been stripped of some non-public info, but basically it just performs a POST request with JSON data. [Controller getSQLHost] just returns a URL - the base domain.
+(NSURLConnection*)initiatePOSTwithJSONDictionary:(NSDictionary*)dictionary toURL:(NSString*)urllocation withDelegate:delegate {
NSMutableDictionary *connectionDictionary = [[NSMutableDictionary alloc] init];
if (dictionary) {
[connectionDictionary setObject:dictionary forKey:#"input"];
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:connectionDictionary options:kNilOptions error:nil];
NSURL *url = [NSURL URLWithString:[[Controller getSQLHost] stringByAppendingString:urllocation]];
NSString *postLength = [NSString stringWithFormat:#"%i", (int)[jsonData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
return [[NSURLConnection alloc] initWithRequest:request delegate:delegate];
}
Does you delegate implement connectionShouldUseCredentialStorage ? (or respond with YES)
I think the device's keychain is used when this method returns yes which may explain the persisting failure beyond the life time of the running application and why rebooting or otherwise resetting network connectivity "fixes" it. If an authentication failure has been recognized once, it may linger in the key chain for a little while which would then respond immediately without actually going to the server.
What would cause the authentication to register as a failure in the keychain in the first place may depend on a variety of factors. It could be as simple as a typo in the saved password or more convoluted such as some certificate expiration preventing the SSL layer from establishing a secure link.
You're creating NSURLConnections on the current runloop. How many are active at any one time? Have you considered using an NSOperationQueue so that you don't get bitten by load bugs?
Is your delegate thread-safe? If not, that could explain the sporadic-ness of the bug.
You say you don't see the problem often, but others do. Can you borrow their devices and maybe even them and their usage patterns and thus get to see the problem more often?

AFNetworking 2 and background tasks

I have a question about AFNetworking 2 and background downloads/uploads thanks to the new iOS7 NSURLSession background requests
Is this automatically handled by my AFHTTPRequestOperationManager ? Does it automatically set my requests'session to background mode?
I saw that the AFURLSessionManager Has a setDidFinishEventsForBackgroundURLSessionBlock Method but I wonder if everything is automatic?
If my app is killed or suspended, will requests keep on going? How can I get a callback when my app is relaunched?
Thanks a lot for your help!
AFHTTPRequestOperationManager uses the old NSURLConnection so that doesn't facilitate background downloading.
AFURLSessionManager uses NSURLSession under the hood so that does. I think you still need to configure the NSURLSession appropriately.
"The NSURLSession class supports background transfers while your app is suspended. Background transfers are provided only by sessions created using a background session configuration object (as returned by a call to backgroundSessionConfiguration:)."
Suggested reading:URL Loading System

Does AFNetworking 2.0 Supports Background task? - iOS 7

i am using Afnetworking 2.0 library with NSURLSession.
i found in AFURLSessionManager they configure Session with default session , so if i need to download images in background then i have to set Session with Background configuration.
So , I have to change AFNetworking library for that or is there any other way for that in AFNetworking 2.0.
From Using NSURLSession:
The NSURLSession class supports background transfers while your app is suspended. Background transfers are provided only by sessions created using a background session configuration object (as returned by a call to backgroundSessionConfiguration:).
You must configure your AFHTTPSessionManager to use the background session configuration if you want to do this:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:#"com.myApp.backgroundDownloadSession"]
AFHTTPSessionManager *backgroundManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
AFNetworking will set itself as the delegate. From the NSURLSession docs:
[T]he delegate will be retained until after the delegate has been sent the URLSession:didBecomeInvalidWithError: message
As a result, your manager will stick around as long as this session does.
Two side notes:
You should probably use use a separate AFHTTPSessionManager for background transfers (large downloads, etc.) You don't want literally all requests to be assigned a background URL session.
In case you want to retrieve the response without AFNetworking, note what the background session identifier is ('com.myApp.backgroundDownloadSession' in my sample code):
An identifier for the new session configuration that is unique for your app. Your app can retrieve the download or the upload response later by creating a new background session with the same identifier.

Continue download in background

I am creating an application wherein I am downloading some data from server. While going in background I want that connection should continue running so that data can be downloaded. I know there is method in appDelegate
- (void)applicationDidEnterBackground:(UIApplication *)application
which is called when application enters background. But as the connection is created in viewController, how can it be managed in appDelegate?
Also is/are there other way(s) this can be done? I have gone through this link but is there a something simple to implement?
One way to do some operations that continue in the background is to create a separate thread to do the downloading. Inside the thread, bracket your download operations between calls to beginBackgroundTaskWithExpirationHandler: and endBackgroundTask. You don't need to check to see whether you are running in the background or not, you just always call these two methods.
// Tell iOS this as a background task in case we get backgrounded
UIBackgroundTaskIdentifier taskId = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:NULL];
//----------------------------------------------
// Perform your download operations here
//----------------------------------------------
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
// Tell iOS that we are done with stuff that needed to keep going even if backgrounded
[[UIApplication sharedApplication] endBackgroundTask:taskId];
[edit]
Sorry I was incorrect, as was pointed out in the comments you can extend the time limit you have to perform operations once/before your app goes into the background. Here is Apple's Official Documentation
I don't know how you handle your data downloading exactly. But you can take a look at ASIHTTPRequest. It is very simple and straightforward, and works with ARC if you set the compiler flags to -fno-objc-arc. With this you only have to use
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setShouldContinueWhenAppEntersBackground:YES]; //For iOS 4.0 and up
And that works.
Here you can see how ASIHTTPRequest works
Hope it helps!

Resources