Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiple NSURLConnections. How to identify which Async call

I am intending to create 2 requests using NSURLConnection. When the server responds and calls connectionDidFinishLoading it passes in the connection as the parameter, but how do I identify which connection is passed in?

like image 255
Xetius Avatar asked Sep 12 '09 18:09

Xetius


4 Answers

Save both NSURLConnection objects as member variables of whatever delegate object you passed to connectionWithRequest:delegate:. Then you can just compare each of those to the NSURLConnection passed to connectionDidFinishLoading:, and respond appropriately:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (connection == firstConnection) {
        // do something
    }
    else if (connection == secondConnection) {
        // do something else
    }
}

Another slightly more object-oriented option would be to create two different delegate objects, each of which knows how to deal with each each type of connection. Then just pass the appropriate delegate when you create each connection. That way you don't need to check to see which connection you have, because each delegate will only receive connectionDidFinishLoading: for its own connection.

like image 56
cduhn Avatar answered Sep 29 '22 09:09

cduhn


I prefer different delegates for each connection, too. Although it's a bit of overhead. Fortunately, you can simplify things by using blocks. It's a new feature that doesn't exist in standard SDK yet, but there is 3rd-party framework called PLBlocks that you can use already. Here is an article on how to use them, it also contains example for NSURLConnection.

This is the client code making HTTP request with block callback:

NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]];
[NSURLConnection sendAsynchronousRequest:req onCompletionDo: ^(NSData *data, NSURLResponse *res, NSError *err) {
    NSLog(@"data: %ld bytes. res: %@, error: %@", (long)[data length], res, err);
    [cell.activity stopAnimating];
}];
like image 23
zakovyrya Avatar answered Sep 29 '22 09:09

zakovyrya


I used to create a custom wrapper around NSURLConnection, too, but I've now switched over to ASIHTTPRequest. This is a fantastic library providing much more flexibility and features than NSURLConnection. Have a look and give it a try, it's really worth it.

like image 37
Daniel Rinser Avatar answered Sep 29 '22 07:09

Daniel Rinser


What I do in my projects is create a wrapper class for the connection. This way, you can keep a new instance for each connection you need, and maintain these classes in another manager class.

Something like [AsynchronousConnection initWithURL:delegate:selector:]

Then you can be ensure the right thing is called when the NSURLConnection is done/failed.

like image 38
coneybeare Avatar answered Sep 29 '22 09:09

coneybeare