NSURLConnection delegate methods are not called

IphoneNsurlconnectionNsurlprotocol

Iphone Problem Overview


I am trying to create a simple NSURLConnection to communicate with a server using a GET request. Connection works well, but delegates methods of NSURLConnection are never called..

Here is what am doing:

NSString *post = [NSString stringWithFormat:@"key1=%@&key2=%@&key3=%f&key4=%@", val1, val4, val3, val4];
    
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease] ;

[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.domain.com/demo/name/file.php?%@", post]]];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];

Have implemented the following delegate methods, but none of them is called..

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	NSLog(@"did fail");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
	NSLog(@"did receive data");
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	NSLog(@"did receive response ");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
	NSLog(@"did finish loading");
	[connection release];
}

Am I missing something?

Iphone Solutions


Solution 1 - Iphone

Try running the operation on main thread:

NSURLConnection * connection = [[NSURLConnection alloc] 
                                initWithRequest:request
                                       delegate:self startImmediately:NO];

[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] 
                      forMode:NSDefaultRunLoopMode];
[connection start];

Solution 2 - Iphone

Are you calling this on a background thread? If you are performing this on a background thread, the thread is probably exiting before the delegates can be called.

Solution 3 - Iphone

Try to check length for the received response it should not getting 0 byte of data.

Solution 4 - Iphone

Apart from checking if the request is called from the main thread, you can check if you give back execution time to the system (if you exit "main"). I had some test code that would stay in a loop until the delegate was called : it would never be called, because the system needs to do stuff in order for the delegate to be called, in the main thread.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionManish AhujaView Question on Stackoverflow
Solution 1 - IphoneArtView Answer on Stackoverflow
Solution 2 - Iphonevisakh7View Answer on Stackoverflow
Solution 3 - Iphonesanjeev sharmaView Answer on Stackoverflow
Solution 4 - Iphoneuser3292568View Answer on Stackoverflow