Wednesday, October 21, 2015

Converting a synchronous API into an asynchronous API

Normally in iOS it is always good to go for an asynchronous API. Because we should not make the UI freeze due to synchronous API calls. Let's first create a synchronous method which take some time to return.
- (NSString*)methodSync {
    for (int i = 0; i < 20; i++) {
        [NSThread sleepForTimeInterval:1.0];
    }
}
If we can turn this into a block based async method, it would be nice. So this is what you should do.
  1. Call the  synchronous method in a background thread
  2. when the execution of the method finishes, we can get the result
  3. The result can be processed by a block created by the user

This is the asynchronous block based implementation.
-(void)methodAsync:(void(^)(NSString *rslt))completionHnadler {
    NSString __block *res;
   
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        res = [self methodSync];
    });
    dispatch_group_notify(group, queue, ^{
        completionHnadler(res);
    });
}
Here I am using dispatch groups to wait till the synchronous method finishes. This is how to call the new method
[self methodAsync:^(NSString *rslt) {
        NSLog(rslt);
    }]; 
For any query, feel free to contact me via my linkedin profile.