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:
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:
+ (void)sendAsynchronousRequest:(NSURLRequest *)
NSData *data,
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.
request
queue:(NSOperationQueue *)queue
completionHandler:(void (^)(NSURLResponse *response,NSData *data,
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
Post a Comment