Get Updates By E-mail 

Article Written By:
Johann Dowa

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.


  •  
  •  
  •  
  •  
  •  

Submit A Resource

Have you created a useful tutorial, library or tool for iOS development that you would like to get in front of our 300,000+ monthly page views from iOS developers?

You can submit the url here.

The resources we feel will appeal to our readers the most will be posted on the front page.

Comments