A Library Adding Promises To Objective-C With Categories For Asynchronous Operations In The iOS SDK

Promises are a great way to clean up asynchronous code and here’s a library from Max Howell that provides a promises implementation in Objective-C called PromiseKit.

PromisesKit adds a category for all one-time asynchronous operations (such as NSURLConnection UIactionSheet, CLLocationManager…) in the iOS SDK. You can also create your own promises, and attach them to third-party libraries.

This example from the readme shows how with PromisesKit you can take this messy asynchronous code:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSString *md5 = md5(email);
    NSString *url = [@"http://gravatar.com/avatar/" stringByAppendingString:md5];
    NSURLRequest *rq = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendAsynchronousRequest:rq queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        UIImage *gravatarImage = [UIImage imageWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imageView.image = gravatarImage;
        });
    }];
});

And turn it into this clean code (with explanations included in this example):

dispatch_promise(^{
    // we’re in a background thread
    return md5(email);
}).then(^(NSString *md5){
    // we’re back in the main thread
    // this next line returns a <code>Promise *</code>
    return [NSURLConnection GET:@"http://gravatar.com/avatar/%@", md5];
}).then(^(UIImage *gravatarImage){
    // since the last <code>then</code> block returned a Promise,
    // PromiseKit waited for it to complete before we
    // were executed. But now we’re done with its result,
    // so let’s set that Gravatar image.
    self.imageView.image = gravatarImage;
});

It’s also very easy to handle error handling with promises like in this example:

#import "PromiseKit.h"

[NSURLConnection GET:@"http://api.service.com/user/me"].then(^(id json){
    id name = [json valueForKeyPath:@"user.name"];
    return [NSURLConnection GET:@"http://api.service.com/followers/%@", name];
}).then(^(id json){
    self.userLabel.text = @(json[@"count"]).description;
}).catch(^(NSError *error){
    //…
});

You can find PromiseKit on Github here.

A nice implementation of promises in Objective-C.

FacebookTwitterDiggStumbleUponGoogle Plus

Original article: A Library Adding Promises To Objective-C With Categories For Asynchronous Operations In The iOS SDK

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

Leave a Reply

Your email address will not be published. Required fields are marked *