Consuming web services and notifying your app about it on Objective C

Since almost the beginning of my exploits as an iOS developer I've been working on several apps consuming web services and one big problem has been notifying different areas of my app that certain event has been updated. My first genius idea was to create my own home brew of notifications using the observer pattern. It wasn't all that bad, but then a while later I realized that I was reinventing the wheel, so I resorted to the one and only NSNotificationCenter.

Enter NSNotificationCenter


According to Apple on the docs for the notification center, this is the definition:

An NSNotificationCenter object (or simply, notification center) provides a mechanism for broadcasting information within a program. An NSNotificationCenter object is essentially a notification dispatch table.

So, this was my observer! How does it work you say? Let's get to it! But before, let's get into context. What I have is a class called ServiceBase which is the base class (duh!) for all classes consuming services. The interface definition for the class looks a bit like this...

 @interface ServiceBase : NSObject<ASIHTTPRequestDelegate>
  - (void) performWebServiceRequest: (NSString*) serviceUrl;
  - (void) triggerNotificationWithName: (NSString*) notificationName andArgument: (NSObject*) notificationArgument;
  - (NSString*) getServiceBaseUrl;
 @end
 

The class has been simplified and the actual class has a few other things that depend more on how I work, but you get the point. However, given the idea of this post, I'm going to concentrate more on the notification side of the class. However, we do need to get some sort of example here going on and to get that done, let's take a look on the performWebServiceRequest method.

- (void) performWebServiceRequest: (NSString*) serviceUrl
{
    if (!self.queue) {
        self.queue = [[NSOperationQueue alloc] init];
    }
    
    NSURL *url = [NSURL URLWithString: serviceUrl];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request addRequestHeader:@"accept" value:@"text/json"];
 
 [requestion setCompletionBlock: ^{
  //this will keep the self object reference alive until the request is done
  [self requestFinished: request];
 }];
 
    [self.queue addOperation: request];
}
 

Now, we have this simplified method that creates a request, sets the requestFinished method as the completion block and queues up the request. Now, I said I would focus on the notifications, but one thing to consider here:

 [requestion setCompletionBlock: ^{
  //this will keep the self object reference alive until the request is done
  [self requestFinished: request];
 }];
 

Keep in mind, that this sentence will preserve the reference to self until the request is finished, so it's not autoreleased by ARC, however, the way I use services on my app, each service works as a singleton (or quite close to that) and keeping the reference is not a problem because you are not creating one new instance of each service class every time you make a request. This also solves an issue with ASIHttpRequest loosing the reference to the delegate before the service is complete, however, that's a story for another day. Now, moving on the the end of the request...

- (void)requestFinished:(ASIHTTPRequest *)request
{
    JSONDecoder* decoder = [[JSONDecoder alloc] init];
    NSData * data = [request responseData];
    NSArray* dictionary = [decoder objectWithData: data];

    for (NSDictionary* element in dictionary) {
  [self triggerNotificationWithName: @"ItemLoaded" andArgument: element];
    }
}
 

When the request is finished, it will only convert the data received, notice that this is a simple scenario, and make a notification that an Item has been loaded using the [triggerNotificationWithName: andArgument] method. Now, into the actual notification method...

- (void) triggerNotificationWithName: (NSString*) notificationName andArgument: (NSObject*) notificationArgument
{
    NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];
   
 if ( notificationArgument == nil )
 {
  [notificationCenter postNotificationName: notificationName  object: nil];
 }
 else
 {
  NSMutableDictionary * arguments = [[NSMutableDictionary alloc] init];
  [arguments setValue: notificationArgument forKey: @"Value"];
  [notificationCenter postNotificationName: notificationName  object:self userInfo: arguments];
 }
}
 

Now, we only need to subscribe to a notification and retrieve the value which is very simple, take this example inside a UIViewController:

- (void) viewDidLoad
{
 NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];
 [notificationCenter addObserver: self selector: @selector(authenticationFinished:) name:@"AuthenticationCompleted" object: nil];
}

- (void) itemLoadedNotificationReceived: (NSNotification*) notification
{
 NSDictionary* itemLoaded = [notification.userInfo valueForKey: @"Value"];
    // Do something with the item you just loaded
}
 


In the itemLoadedNotificationReceived method the app will receive a notification when each item is loaded. This may not be the best example, because when you're loading several items, they normally go into a cache to be loaded from a UITableView afterwards, but this idea should get you going.

Do you use a different approach? Do you normally use it like this? Well, if you have anything at all to say, feel free to leave it in the comments!

No comments:

Post a Comment

Commenting is allowed!