Skip to main content

Asynchronous Request with NSOperationQueue

Today post is about how to run a asynchronous task in NSOperationQueue.  Generally we do not run a Asynchronous task in NSOperationQueue. It is also not recommended for any programmer to do that. This post is only for learning purpose what will happen if we schedule a asynchronous task in a queue and how can we complete that task:). So let us move to the learning:


NSOperationQueue:

In iOS NSOperationQueue is a class, which provide a way to perform operation concurrently. We also have others way to perform concurrent operation:

1) GCD
2) NSThread
3) pThread

NSOperationQueue is a wrapper on GCD, which provides a very convenient way to execute operation concurrently. To create a Queue for Operation you have to simply allocate a object of the class:

NSOperationQueue* opertionQueue = [[NSOperationQueue alloc] init];

For this post let suppose you are making a queue to handle all Http request in your application. So i want to create a queue in Handler class only once.

HTTPHandler.h

@interface HTTPHandler : NSObject


+ (instancetype) sharedInstance;
- (NSOperationQueue*) operationQueue;

@end


HTTPHandler.m

@implementation HTTPHandler{
    NSOperationQueue*       _operationQueue;
}


static HTTPHandler* sharedInstance = nil;

+ (instancetype) sharedInstance{
    static dispatch_once_t once;
     dispatch_once(&once, ^{
        sharedInstance = [[HTTPHandler alloc] init];
        operationQueue = [[NSOperationQueue alloc] init];
        operationQueue.name = @"com.sh.queue";
     });
    return sharedInstance;
}

- (NSOperationQueue*) operationQueue{
    return operationQueue;
}

We are done with operation queue initialiaztion. If you want to study about NSOpertionQueue you can follow the link.

NSOperation:

It is an abstract class that represents a task. A task can be download data from server, Image resizing, Data read from local storage etc. 

It provides functionality related to a task. Developer can cancel a task or can add dependency between the tasks. Advantages of the class developer need to focus only to implement the task logic. Rest feature related to task management and execution provide by this abstract class. We need to override the main method of NSOperation class to implement own task.


I am using this class to create an operation that will execute the asynchronous task in the main method. Which is basically a hit to a url.

SampleOperation.h

#define URLString       @"http://www.google.com"

@interface SampleOperation : NSOperation

@property (nonatomic, assign)BOOL isComplete ;

@end

SampleOperation.m


@implementation SampleOperation

- (id) init{
    self = [super init];
    return self;
}
//Main method of Operation

- (void)main {
    @autoreleasepool {
        HttpConnection* connection = [[HttpConnection alloc] initWithDelegate:self];
        [connection startAsyncRequestWithUrl:URLString];
    }
}

#pragma mark - HTTP Delegate
- (void) httpConnection :(HttpConnection*)connection didGetResponse:(NSURLResponse*)response{
    
}

- (void) httpConnection :(HttpConnection*)connection didFinishCompleteWithData:(NSData*)data{
}

- (void) httpConnection :(HttpConnection*)connection didFailWithError:(NSError*)error{

}


@end

So in above example I make an asynchronous request and waiting for the response in delegate methods. These delegate methods are not NSURLConnectionDelegate.

I have prepared an HTTPConnection class. You can take the reference from the link.

Will we get call in this delegate method?
No.

The reason is same as explained in the NSThread post. The Thread that initiates the request terminated.

So how can we complete an asynchronous request on a queue.  There are two approaches which is explained below:

Solution 1 (Recommended Solution):

This Solution is based on the method provided in NSURLConnection class. In which we can specify the Operation queue reference on which the operation need to execute. 

+ (void)sendAsynchronousRequest:(NSURLRequest *)request                          queue:(NSOperationQueue *)queue              completionHandler:(void (^)(NSURLResponse *response,
                                          NSData *data,
                                          NSError *connectionError))handler 

No need to define operation in this case :). Just create an NSURLRequest and Operation Queue object and pass it to the connection class method with completion handler block. Block has all the parameter, which we can check whether we get proper response or error. If no error then we can check the data.

Example:

 NSURL *url = [NSURL URLWithString:@"https://www.google.com"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        // Send the request!
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:opertionQueue
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                   if (!response) {
                                       //Unable to reah server
                                   }else if (error) {
                                       //Check error and Perform action
                                   }else if (!data) {
                                       //Return No data Found
                                   } else {
                                       //Do perform action on data
                                   }
                               }];

Solution 2:

This solution is not recommended solution but you can use in case you do not have any API like this for asynchronous request.
The solution based on the approach that we would stop the thread to die by modifying its run loop execution. Following is the example of modified Sample Operation:

SampleOperation.m

@implementation SampleOperation

- (id) init{
    self = [super init];
    return self;
}
//Main method of Operation

- (void)main {
    @autoreleasepool {
        HttpConnection* connection = [[HttpConnection alloc] initWithDelegate:self];
        [connection startAsyncRequestWithUrl:URLString];
        while(1){
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; 
            sleep(2);
            if(self.isComplete){
                break;
            }
        }
    }
}

#pragma mark - HTTP Delegate
- (void) httpConnection :(HttpConnection*)connection didGetResponse:(NSURLResponse*)response{
    
}

- (void) httpConnection :(HttpConnection*)connection didFinishCompleteWithData:(NSData*)data{
    self.isComplete = true;
}

- (void) httpConnection :(HttpConnection*)connection didFailWithError:(NSError*)error{
    self.isComplete = true;
}

@end

We are calling the run mode method it will check for the event if no event is there it return immediately. Then we are executing the sleep in thread. This whole execution is never ending while.
So once we got the response then we can get out from the never ending while by checking is complete.

There are other methods also like we can schedule the run loop to listen to particular port and when we get the response we can stop that.

So this is not good way but we can use when needed.

You can download the full source code by this method from the link:


Comments

Popular posts from this blog

Implement orientation modes in iPhone Hybrid Applications

Let suppose you are working on a hybrid application which runs only in single (portrait) mode. One day a requirement come that PDF and Doc Viewer (HTML Page) should support both (landscape, portrait) mode. Your Application loads all the HTML content from the local html files and you need to implement the above functionality only for one HTML file. Let break the above task in the modules: Step 1: Application should detect when the PDF and Doc viewer is open in application. I setup location.href tag in html to " docvieweron:// " and " docvieweroff:// " when page is open and closed respectively. In this way I am getting a delegate callback in web view: WebViewDelegate: - ( BOOL ) webView:( UIWebView *)webView shouldStartLoadWithRequest:( NSURLRequest *)request   navigationType: ( UIWebViewNavigationType )navigationType {          NSString * urlString = [[request URL ] absoluteString ];...

iOS8 UIWebView Remove or Modify Keyboard Toolbar

Remove Toolbar: One of my client requirements is to remove the default toolbar for the keyboard. I found numerous examples for iOS7 to remove toolbar from the keyboard window. But it did not work for iOS8. So i came to following solution after some Research on Google: Step1:   First we need to add observer for keyboard notification: [[ NSNotificationCenter defaultCenter ]  addObserver : self selector : @selector ( removeKeyboardTopBar :) name : UIKeyboardWillShowNotification object : nil ]; Step 2: We need to implement the method for observer: - ( void )removeKeyboardTopBar {     } Step 3: Find the keyboard window from all the application  windows:   - ( void )removeKeyboardTopBar {     UIWindow *keyboardWindow = nil ;     UIView * toolBarContainer = nil ;     NSArray * windows = [[ UIApplication sharedApplication ] windows ];     for ( U...