This HTTP call seems to be hanging and I can't see why. The logging line after the call never runs.
I'm almost certainly doing something extremely stupid, but if anyone can spot what it is I'd be grateful. As far as I can see my code is equivalent to the docs.
It doesn't seem to matter what URL I use, and the HTTP request is never logged by the server (if pointed at one).
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
NSURLResponse *res = nil;
NSError *err = nil;
NSLog(@"About to send req %@",req.URL);
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&err];
NSLog(@"this never runs");
Any ideas?
Update
Thanks to everyone who's posted so far. Still seeing the problem. A bit more detail:
sendAynchronousRequest
but in this instance I need to pass a return value (and I'm not on the main thread), so sendSynchronousRequest
is the only option I know of.NSURLCache
protocol, specifically the cachedResponseForRequest
method, which requires I return a NSCachedURLResponse
Run the request in a background queue so it does not block the main thread where UI updates occur:
dispatch_queue_t myQueue = dispatch_queue_create("myQueue", NULL);
// execute a task on that queue asynchronously
dispatch_async(myQueue, ^{
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
NSURLResponse *res = nil;
NSError *err = nil;
NSLog(@"About to send req %@",req.URL);
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&err];
});
Add delegate <NSURLConnectionDataDelegate>
NSURL *url = [[NSURL alloc]initWithString:[NSString stringWithFormat:@"Your string here"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];//It will start delegates
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[received_data setLength:0];//Set your data to 0 to clear your buffer
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[received_data appendData:data];//Append the download data..
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Use your downloaded data here
}
This method more better to download data.. It wont use main thread so the app wont hang.. I hope it will be more useful for you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With