Search code examples
objective-ccocoahttpclass-design

How to set up HTTP connection in a special class?


I want to create a class to handle all the HTTP connection work for other classes(in order to avoid writing codes repeatedly). I call it ConnectionCenter(subclass of NSObject) and add the following codes to it:

-(void)connect:(NSString *)strURL obj:(ConnectCenter *)objConnect
{
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:strURL]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:objConnect];
    if (theConnection) 
    {
        // receivedData is declared as a method instance elsewhere
        receivedData = [[NSMutableData data] retain];
    } 
    else 
    { 
        // inform the user that the download could not be made
    }

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere
    [receivedData appendData:data];
}

And other classes call it by passing a URL and an object of ConnectionCenter. But the method 'didReceiveData' in ConnectionCenter is not called. Any ideas about what's the problem with it?


Solution

  • You'll need to call [theConnection setDelegate:self] after you setup the connection, since connection:didReceiveData: is a delegate method.

    Read the documentation for more info.