I read a lot of posts repeating the same thing: when you use NSURLConnection, delegate methods are not called. I understand that the Apple document is incomplete and refers to outdated methods, which is a shame, but I cannot find a solution.
Code for the request:
// Create request NSURL *urlObj = [NSURL URLWithString:url]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlObj cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30]; [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"]; if (![NSURLConnection canHandleRequest:request]) { NSLog(@"Can't handle request..."); return; } // Start connection dispatch_async(dispatch_get_main_queue(), ^{ self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; // Edited });
... and code for delegate methods:
- (void) connection:(NSURLConnection *)_connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"Receiving response: %@, status %d", [(NSHTTPURLResponse*)response allHeaderFields], [(NSHTTPURLResponse*) response statusCode]); self.data = [NSMutableData data]; } - (void) connection:(NSURLConnection *)_connection didFailWithError:(NSError *)error { NSLog(@"Connection failed: %@", error); [self _finish]; } - (void) connection:(NSURLConnection *)_connection didReceiveData:(NSData *)_data { [data appendData:_data]; } - (void)connectionDidFinishDownloading:(NSURLConnection *)_connection destinationURL:(NSURL *) destinationURL { NSLog(@"Connection done!"); [self _finish]; }
There are not many mistakes here, but I have seen a few things:
- No matter what happens,
didReceiveData
is never called, so I get no data - ... but the data is being transmitted (I checked with
tcpdump
) - ... and other methods are called successfully.
- If I use
NSURLConnectionDownloadDelegate
instead of NSURLConnectionDataDelegate
, everything works, but I can not hold the downloaded file (this is a known error). - The request is not freed until terminated by improper memory management
- Nothing will change if I use a standard HTML page somewhere on the web, as my URL
- The request is sent from the main queue
I do not want to use a third-party library, since, ultimately, these requests should be included in my own library, and I would like to minimize dependencies. If I need to, I will use CFNetwork
directly, but it will be a huge pain in you-know-what.
If you have any ideas, this will help a lot. Thanks!
source share