Skip to content

Handling multiple CPURLConnections with a common delegate

February 4, 2011

This week, Sheehan and I came across a problem that I’m sure others have too. The solution was obvious, once we figured it out.

The issue is: how can a single class that creates multiple asymchronouse CPURLConnections handle the responses.

Obviously, the class itself can only have a single delegate method:

-(void)connection:didReceiveData:

Our first thought was to create separate delegate classes just to handle those connections and set the delegate of the connection to an instance of that class. In fact, that turned out to be a good solution for requests that were made from different controllers.

But we still had a case, where we wanted to have the connection handled in the same class because, upon receipt of the response, certain actions had to take place. The solution we came up with turned out to be quite simple. We assigned “private” variables to those connections and in the delegate method, checked if the connection was the equal to the private variable.

var request = [[CPURLRequest alloc] initWithURL:[CPURL URLWithString:@"http://api.myserver.com]];

_firstConnection= [CPURLConnection connectionWithRequest:request delegate:self];

request = [[CPURLRequest alloc] initWithURL:[CPURL URLWithString:@"http://api.myserver.com/posts]];

_secondConnection = [CPURLConnection connectionWithRequest:request delegate:self];

-(void)connection:(CPURLConnection)connection didReceiveData:(CPData)data
{
    if (connection == _firstConnection) {
        [something doThis];
    }
    if (connection == _secondConnection) {
        [something doThat];
    }
}

– Dan

Advertisements

From → Tips & Tutorials

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: