NSURLConnection times out after reopening app - ios

In my app I use a NSURLConnection to upload some content.
Everything works fine except when I reopen the app after like one hour.
The NSURLConnection will timeout every time at the first try. After that the app works fine.
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:delegate];
[connection start];
Using [NSURLConnection sendAsynchronousRequest:request...] also leads to a timeout.
On another thread on the Apple developer forum somebody suggested to run a packet trace, which I did. The request does not seem to be sent.
I'm a bit out of ideas, do you have one ?
Thanks a lot!

Related

wifi is connected and internet is not available iOS

My question is same as this question, but don't get a proper answer.
If I am connected to wifi, but internet is not available/gone it should be notify. Alslo tested using Apple Reachability demo but still its not working.
Steps to reproduce:
1) connect iPhone using tethering on another device.
2) run the apple rechability demo.
3) turn off the cellular data on another device on wich iPhone is connected.
You can simply call the below code and then call NSURLConnection delegate methods. This way even if wifi is connected and internet not available it can be detected.
NSMutableURLRequest *headerRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.google.com"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0];
headerRequest.HTTPMethod = #"HEAD";
self.headerConnection = [[NSURLConnection alloc] initWithRequest:headerRequest delegate:self];

Network connection lost when uploading large videos

I am developing an video sharing app. When I am trying to upload videos larger than 10MB NSURLConnection get lost and I got error NSURLErrorDomain Code=-1005 "The network connection was lost." . Video, less than 10 MB are uploading.Can resolution of video be an issue here?? Resolution of my video is 1280*720 .
Can anyone help me to understand issue here. This is my code for connection
NSString *urlString = [[NSString alloc]initWithString:[NSString stringWithFormat:WEBSERVICE_URL]];
urlString=[urlString stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:100];
[request setHTTPMethod:#"POST"];
This is not duplicate of NSURLConnection GET request returns -1005, "the network connection was lost" because
I am not using third party library for connection and not using simulator. I had tried every thing from that answer.
You might be hitting various timeouts—either the NSURLConnection timeout or a timeout on the server side. iOS may ignore the timeout value you specify, BTW. Or you could just be losing the network connection because your device decided to power down the cellular or Wi-Fi hardware to conserve power. Hard to say which. Or your Wi-Fi connection could have dropped because it missed too many beacons from the access point for some reason. Or....
My advice would be to upload large files a piece at a time, and then assemble the pieces on the server. That way, when (not if) the connection fails, you can re-upload the chunk that only partially transferred, and then continue uploading additional chunks until you've uploaded the whole thing.
See also the Content-Range HTTP header. Obviously, this requires your server-side code to support that functionality, but it is worth the extra effort. :-)
BTW, you forgot to set the Content-Type header.

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?

How do iOS HTTP request retries work?

I'm using NSURLConnection to send an HTTP request and running it with
[[NSURLConnection alloc] initWithRequest:self.request delegate:self];
where "self.request" is a configured NSMutableURLRequest object. Upon a network failure and callback to
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
I'd like to cancel the request and write the payload to file to be uploaded later. However if I reconnect too quickly the payload ends up getting sent still (and I later send the same payload from the file). In the failure callback, I've tried to use
[connection cancel];
But the http request still goes through upon reconnecting within a few seconds. Is this due to some retry mechanic that I can disable?
From Apple's docs on didFailWithError:
// Once the delegate receives this message, it will receive no further messages for connection.
So I'd say you have a bug somewhere else in the code. Once that delegate message is called, the connection is done and it will never be restarted unless you do so.
From the question it seems like you are trying to cancel the connection in the failure delegate method, is that correct? That should not be necessary since the connection is already dead. I'm also a bit confused when you say you "retry to quickly". I don't see any "retry" code so it would help if you could post that too.
Can you post more code to help diagnose the issue?

NSNetwork error after starting NSURLSessionDownloadTask

I use NSURLSession to download files in background. Here is how I start a new NSURLSessionDownloadTask:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self nextURL]];
_task = [[self downloadSession] downloadTaskWithRequest:request completionHandler:nil];
[_task resume];
After calling resume, I encountered the following error:
nsnetworkd[1557] <Error>: Couldn't add download <SSDownload: 0x16d63a20>: 958545229883046269 to download manager
After this, no delegate methods were called (it seems like the session was killed). The internet connection was ok (Safari was able to open websites).
It occurred only once on iOS 7.0.4. Can someone please explain what could this error mean? Is this an iOS 7.0.x bug or is there a good workaround?

Resources