Search code examples
iosnsurlconnectionnsoperationqueue

NSURLConnection is not working in NSBlockOperation while operation added to NSOperationQueue


I am using NSURLConnection in NSBlockOperation and i am adding this operation to NSOperationQueue.But it is not working.When i am calling start method of NSBlockOperation then it working but it is not working when i am adding NSBlockOperation to NSOperationQueue.

please can anyone help me ???

NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue setMaxConcurrentOperationCount:1];

NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
    NSURL *url = [NSURL URLWithString:@"http://api.kivaws.org/v1/loans/search.json?status=fundraising"];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    NSURLConnection  *connection1 = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    [connection1 start];
}];

NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
    NSURL *url = [NSURL URLWithString:@"http://urls.api.twitter.com/1/urls/count.json"];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];


    NSURLConnection  *connection2 = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    [connection2 start];
}];

[operation2 addDependency:operation1];

[operationQueue addOperation:operation1];
[operationQueue addOperation:operation2];

I have also implemented NSURLConnectionDataDelegate as:

  • (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  • (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response

Please help Thanks


Solution

  • I see at least two issues with your code:

    1. You mustn't call - (void)start after - (id)initWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate. It starts by itself.
    2. - (id)initWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate is asynchronous so you have to keep your operation alive all that time while it works as well as your operationQueue shouldn't be a "stack" variable.

    How to fix it easily:

    1. Use + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error inside your blockOperations. It blocks current thread while performing loading.

    Example:

    NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
        NSURL *url = [NSURL URLWithString:@"http://urls.api.twitter.com/1/urls/count.json"];
        NSURLRequest *req = [NSURLRequest requestWithURL:url];
    
        NSURLResponse *response = nil;
        NSError *error = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
    }];
    

    There are a lot of other approaches but first one should work perfectly well.