5

I have two request starting one after the other. Starting request like this

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com"]];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
NSURLConnection * connection = [[NSURLConnection alloc]
                                initWithRequest:request
                                delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                      forMode:NSDefaultRunLoopMode];
[connection start];

and another request starting like this.

NSURL *url1 = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.apple.com"]];
NSURLRequest *request1 = [NSURLRequest requestWithURL:url1 cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
NSURLConnection *connection1 = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
[connection1 release];

How can i differentiate between these two in delegate method?

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{}

Don't want to keep any extra class variable for this purpose.

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75
NaXir
  • 2,373
  • 2
  • 24
  • 31
  • Check if the `connection`argument in the callback method is equal to the `connection` or `connection1` variables in your code. – Markus May 06 '13 at 07:17

2 Answers2

4

It's Simple :

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
     if (connection == connection1)
     {
         //It's for connection1.
     }
     else if (connection == connection2)
     {
         //It's for connection2.
     }
}

You can go through this Beautiful SO Question : Managing multiple asynchronous NSURLConnection connections

Community
  • 1
  • 1
Bhavin
  • 27,155
  • 11
  • 55
  • 94
  • In that case i have to keep two class variables Connection1 and Connection 2, as both connection may be working simultaneously. And I am trying to avoid these extra variables. – NaXir May 06 '13 at 07:26
  • In that case, can I ask you why are you using this old approach ? – Bhavin May 06 '13 at 07:29
  • I found it easy to do. Will you please share the new approach? – NaXir May 06 '13 at 07:35
  • The approach shared in link is the thing i needed. Thanks – NaXir May 06 '13 at 07:39
2

take your NSURLConnection objects in .h file and check in your delegate method as Markus has suggested.

or

Subclass your NSURLConnection and then you can add tag property to the connection class while creating, in you delegate methods check for appropriate tag. You can find working tutorial here.

Ankur
  • 5,086
  • 19
  • 37
  • 62