Skip to main content

NSThread with Asynchronous Request

NSThread:

It is class used in Cocoa framework to create a thread.You have to specify a target and selector to create a new thread in objective c. So the selector or method is main entry point of your thread. 


What happen once the thread execute all the code in the method (Thread main routine)?

Thread is terminated after execute all the code in the entry(its main routine) routine. So how we can run an asynchronous request on NSThread ?

What is Async request?

It is non blocking request which permit the application to do other task side by side as request is in continue. So it enhance parallelism in the application.


Now question is how we can prepare a asynchronous request in iOS:

- (void) startAsyncRequestWithUrl:(NSString*)urlString{
    assert(urlString != nil && urlString.length > 0);
    NSURL* url = [[NSURL alloc] initWithString:urlString];
    NSURLRequest* urlRequest = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
    theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    [theConnection start];

}


So above code has an example of asynchronous http request in iOS. As we know we need to implement delegate method  for the Url connection. So our main motive is to understand what happen  when we set the above method as main routine or entry point for NSThred then what will happen ?

So for the all the delegates method and complete HTTP connection file you can download from following link:

HttpConnection Link:

Let come back to our question is delegate call for the connection ? If yes then on main thread or the new thread?

So Just try this code ?

 HttpConnection* conn = [[HttpConnection alloc] initWithDelegate:self];
    NSString* urlString = @"https://imagizer.imageshack.us/v2/235x352q90/716/nkm8.jpg";
    [NSThread detachNewThreadSelector:@selector(startAsyncRequestWithUrl:) toTarget:conn withObject:urlString];

Did you get call in delegates ?

It will not come. Delegate will never be called and the obvious reason is thread terminate (which init the request).

So  now try to call by following method:
[conn startAsyncRequestWithUrl:urlString];

instead of that

 [NSThread detachNewThreadSelector:@selector(startAsyncRequestWithUrl:) toTarget:conn withObject:urlString]; 

Delegate will be called :)

Is there any tactic so that it can work on NSThread as well?

Yes 

RunLoop:

A run loop is event processing loop and it associated with each thread. So your main thread also have run loop. If you add any source of event to run loop then it will execute on the respective thread to which that run loop begin.

So our solution also use the same approach.  The basic idea is we need to busy the run loop of thread so that our thread will not terminated.

We need to busy the run loop associated with NSThread so that our thread should not terminate.
So we need to block the run loop for indefinite time until we did not receive the callback
We can do that by using following method:

- (connectionStatus) startAsyncRequestWithUrl:(NSString*)urlString{
    self.status = connectionSetupStage;
    assert(urlString != nil && urlString.length > 0);
    NSURL* url = [[NSURL alloc] initWithString:urlString];
    NSURLRequest* urlRequest = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:CONNECTIONTIMEOUT];
    theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    
    while(self.status != connectionSucess && self.status != connectionFail){
        BOOL isBlockForInput = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        NSLog(@"Blocked:%d",isBlockForInput);
    }
    return self.status;

}

So we are calling the following run loop method in a loop

[[NSRunLoop currentRunLooprunMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]

By calling above method run loop will be trying to process the input source if any input source not available then it will return immediately. So If it return after delay it means it processed some input and print 1 in that case for above example. 

Can we optimize the code here ?

I think if there is no input source then CPU cycle will waste to processing the loop until it does not have any source.

So we can add sleep method here for the thread like given below:
 

 while(self.status != connectionSucess && self.status != connectionFail){
        BOOL isBlockForInput = [[NSRunLoop currentRunLooprunMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
       sleep(1);
        NSLog(@"Blocked:%d",isBlockForInput);
    }








time depend upon the request if request take time you can increase the sleep time.

You can find more detail of this method here :
Detail:

So done with the today topic.
Please mail me if you need more information on this.




Comments

Popular posts from this blog

What does enable bitcode do in Xcode

Background: Now days compilation process for any language is divided into two parts and same is applicable for objective c. Frontend Compiler (Clang) Backend Compiler (LLVM) Frontend Compiler (Clang):  Responsibility of front-end compiler is to take a source code and convert into intermediate representation (IR).  In case of clang it is LLVM IR.  Backend Compiler(LLVM):  Responsibility of backend compiler is to take a IR as input and convert into object code. LLVM input is bitstream of LLVM IR (Bitcode) and output is sequence of machine instruction(Object code). Each  cpu or processor has different set of  M achine   instruction, So  LLVM output is CPU dependent or it can be executed on specific CPU only.   There may be question in your mind that  1) What is the need to divide into these phases? 2) What is LLVM IR? Can we see the LLVM IR as Output? What is the need to divide into these phases? It is beneficial for both the programming language designer a

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

Shake Effect in iOS

Animation Animation always capture the user attention. We can use animation to update things on the screen.  For developer also animations fascinated things to learn and implement. Today we will try shake effect with Various  API. CABasicAnimation: Here we animate view's frame y coordinate from one position to another position. It is simple example of changing the position with respect to time. CABasic Animation is deal with the single keyframe.                                        y(t) = y 0 + t*d(y) You can use CABasic Animation if you have to play with single value. You need to move object from  one position to another without any intermediate steps. CABasicAnimation * shakeAnimation = [CABasicAnimation animationWithKeyPath: @ "position" ]; shakeAnimation . duration = 0.05 ; shakeAnimation . autoreverses = YES; shakeAnimation . repeatCount = 6 ; CGPoint shakeFromPoint = CGPointMake( self . shakeLabel . center . x,