NSURLConnection is not responding

I am trying to get some data from a url but for some reason nothing happens when I do the following. Neither didReceiveResponse: didReceiveData: didFailWithError: nor connectionDidFinishLoading: reached, unless I add a timeout to my request by doing this: [request setTimeoutInterval:10.0]

That's what I'm doing:

 -(void)getConfigFromServer{ [self getContentAtURL:kUrlGetUser]; } //Va chercher le contenu à l'URL passée en paramètre - (void)getContentAtURL: (NSURL *)url { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSString * userLogin = [userDefaults objectForKey:@"UserLogin"]; NSString * userPassword = [userDefaults objectForKey:@"UserPassword"]; NSURL * urlFinal = [NSURL URLWithString:[NSString stringWithFormat:@"%@", url]]; NSLog(@"Request : %@", [NSString stringWithFormat:@"%@", url]); NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:urlFinal]; [request setHTTPShouldHandleCookies:NO]; [request setTimeoutInterval:10.0]; NSString *sourceString = [NSString stringWithFormat:@"%@:%@", userLogin, userPassword]; NSData * sourceData = [sourceString dataUsingEncoding:NSUTF8StringEncoding]; NSString *authString = [sourceData base64EncodedString]; authString = [NSString stringWithFormat: @"Basic %@", authString]; [request setValue:authString forHTTPHeaderField:@"Authorization"]; [request setValue:@"text/xml" forHTTPHeaderField:@"Accept"]; NSURLConnection * connection=[NSURLConnection connectionWithRequest:request delegate:self]; if(connection){ NSLog(@"Connection started"); receivedData = [NSMutableData data]; }else{ NSLog(@"Error while trying to initiate the connection"); } } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [receivedData setLength:0]; if ([response respondsToSelector:@selector(statusCode)]) { int statusCode = [((NSHTTPURLResponse *)response) statusCode]; if (statusCode >= 400) { [connection cancel]; // stop connecting; no more delegate messages NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:[NSString stringWithFormat: NSLocalizedString(@"Server returned status code %d",@""), statusCode] forKey:NSLocalizedDescriptionKey]; NSError *statusError = [NSError errorWithDomain:@"Error" code:statusCode userInfo:errorInfo]; [self connection:connection didFailWithError:statusError]; } } } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [receivedData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; NSLog(@"Connection failed! Error - %@ %@",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); } -(void)connectionDidFinishLoading:(NSURLConnection *)connection{ [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; [self fetchedData:receivedData]; } 

EDITOR: I still have this problem, and now it is also on the device itself. As I said in the comments, I am using ARC for the first time in this application, and I am using Xcode 4.2.

Any idea?

+3
source share
5 answers

This is an old thread, but this answer might help someone out there.

If you call this on a background thread, check if the thread exits when delegates are called.

Try to do it.

 NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; [connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; [connection start]; 
+5
source

You pass NSURL to your getContentAtURL, but then treat it as if it were a string:

 NSURL * urlFinal = [NSURL URLWithString:[NSString stringWithFormat:@"%@", url]]; 

try changing it to:

 NSURL * urlFinal = [NSURL URLWithString:[NSString stringWithFormat:@"%@", [url absoluteString]]]; 

btw, you know you don’t use your username and password, right?

EDIT:

When you say that receivedData = [NSMutableData data]; What is data?

I think this may be a problem.

I want to use the following to set up a data object when data first arrives:

 - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData { if (receivedData ==nil) { receivedData = [[NSMutableData alloc] initWithCapacity:2048]; } [receivedData appendData:incrementalData]; } 
0
source

I think the problem will be with the server side. Try increasing the TimeoutInterval to 60, so there will be more time to get data from the server. Didn't you get the message “connection timeout” after 10 seconds?

EDIT

Hi, I think you have not reached a solution yet. When I read the code in detail, I found that some statements are confusing.

1) [request setValue:@"text/xml" forHTTPHeaderField:@"Accept"]; replaced by

  [request setValue:@"text/plain" forHTTPHeaderField:@"Accept"]; 

Also turn on

  [request setValue:@"text/plain" forHTTPHeaderField:@"Content-Type"]; 

And finally ...

The error "connection timeout" means that the iPhone is not receiving any data from the server. While the iPhone receives simple information, it calls - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data . Try setting NSLog after each statement to verify that the variables retain the desired value. Try checking the data length - sourceData - before submitting ...

0
source

The error message, as you said in the comments, indicates that the request has been exhausted. I am sure that if you delete the line with the timeout, you will receive either the same answer or the actual data after 60 seconds. Make sure you wait enough, because if your connection is very weak for any reason, the request may not expire after 60 seconds, as it continues to load data.

Is your application in the foreground at launch time? Make sure you do not pause it.

In addition, you say that the server is connected to the network, but your code is disabled. So something is probably wrong with your connection.

In another comment, you say that sometimes it works. Even more indicates that the connection is weak / unreliable or broken.

0
source

Some thoughts here:

  • do not store passwords in UserDefaults, use a keychain for this (maybe you are only testing, I just wanted this to be mentioned)
  • Why are you converting the NSURL to the new NSURL by calling stringWithFormat: on the URL? (Oh, I see that @ade already mentioned this)
  • Is this application with ARC -enabled? If not, your NSMutableData will be auto-implemented too soon, use self.receivedData = [NSMutableData data] , and you will see a failure.
  • Try adding an NSURLConnection instance NSURLConnection and holding it. I think it should work the way you do it now, but I usually stick to it and have never had the problem you are talking about here.
  • It’s strange that your 10 second timeout seems to work, I was not able to get it to work and found that on the iPhone the timeout could not be lower than 240 seconds . Yes, I was also embarrassed about this, but: fooobar.com/questions/88179 / ...
0
source

Source: https://habr.com/ru/post/944012/


All Articles