Consuming RESTful API with RESTframework

As explained in previous post, we’re going to demonstrate how RESTframework handles REST web services. I’ll be consuming a simple Django demo web service created in previous post, so either grab the sources or read the post and build it yourself. Assuming you have this service running on localhost, port 8000, we can continue.

First, download RESTframework from GitHub. With git client, simply type in terminal:

$ git clone git@github.com:ivasic/RESTframework.git

The quickest way to get RESTframework into your project is just including all the files from RFClasses  folder. RF does not have any external dependencies so building shouldn’t be a problem.

RFClasses

RFClasses

Now, we’ll also need JSONKit to parse API response and MBProgressHUD to show some progress. Grab both from GitHub and add to your project.

Fetching objects list

We’ll have 2 view controllers in our demo app. One will be a simple object list and the other one will be, even more simple, view controller for creating a new object. First, we’re going to show how to fetch the object list. We’ll need a GET request to /objects/ URL and we’ll need to parse the JSON array we get in response and show in the table view.

RFRequest* r = [RFRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/"] type:RFRequestMethodGet resourcePathComponents:@"objects", nil];
[MBProgressHUD showHUDAddedTo:self.view animated:YES].labelText = NSLocalizedString(@"Loading...", @"");
[RFService execRequest:r completion:^(RFResponse* response) {
	[MBProgressHUD hideHUDForView:self.view animated:YES];
 
	if (response.error) {
		UIAlertView* aiv = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"") message:response.error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
		[aiv show];
		return;
	}
 
	self.dataSource = [response.dataValue objectFromJSONData];
	[self.tableView reloadData];
}];

So, what we’re doing in this code snippet is:

  • Creating a GET RFRequest with appropriate URL and resource path
  • Attaching MBProgressHUD to our view to show spinner progress
  • Executing RFRequest and defining the block to execute after RFResponse is received
  • Inside this block, we simply check for errors, parse the response, add to our tableView dataSource and reloading the table
You can see all this in action in the project sample attached to this blog post (at the bottom).

Creating new objects

Our view controller for creating new objects is responsible for creating POST requests to /objects/ URL. Again, very simple, you just need to do this:

RFRequest* r = [RFRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/"] type:RFRequestMethodPost resourcePathComponents:@"objects", @"", nil];
 
[r addParam:self.txtName.text forKey:@"name"];
[r addParam:self.lblDate.text forKey:@"date"];
 
[MBProgressHUD showHUDAddedTo:self.view animated:YES].labelText = NSLocalizedString(@"Submitting...", @"");
[RFService execRequest:r completion:^(RFResponse* response) {
	[MBProgressHUD hideHUDForView:self.view animated:YES];
 
	if (response.error) {
		UIAlertView* aiv = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"") message:response.error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
		[aiv show];
		return;
	}
 
	UIAlertView* aiv = [[[UIAlertView alloc] initWithTitle:@"Success" message:@"Success" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
	[aiv show];
 
	[self.navigationController popViewControllerAnimated:YES];
}];

Similar to our previous snippet, but this time we also add some parameters to the request – name and date strings.

This is a brief overview with sample Xcode project of how RESTframework consumes RESTful web APIs. Questions welcomed via comments as usual.

 

Download project: RESTframework demo Xcode project download

REST framework for iOS is now Open Source

I have (finally) open sourced my RESTframework project on GitHub. It aims for simplicity of usage primarily. Querying RESTful web services is really easy now. Supported are iOS versions 4.0 and above and Mac OS 10.6 and above.

Feel free to fork & contribute!

RESTframework on GitHub

Fetching emails from Gmail using Cocoa

I built this contact form for one website (my company’s) and at the time it was least expensive to just shoot out emails to a specific address with user’s messages and email addresses. Naturally, at one point I had to collect those emails & messages and use them so I ran into problem – what’s the easiest way to do that? Fortunately, our email server was GMail so I found a couple of ways to do it, avoid writing IMAP client and the easiest way for me was to use GMail’s built-in RSS feed and simply parse this feed to get what I want. In Cocoa, this should be simple enough but turned out not to be in my case.

Cocoa’s PubSub framework offers a nice way of subscribing to RSS feeds and it was ideal and simple for usage in this particular case. However, I just couldn’t get it to work with GMail’s authentication. I’ll explain below.

First I had to set up GMail account for easier access to the emails. Using search & filters, I found all emails that contained the info I needed and moved them to a separate temporary GMail label I created. At the same time I marked all emails as unread. This is very important because only unread emails appear in RSS feed and without this step, the feed for the label would appear empty.

Now the coding part. Ideally we would simply get PSClient and create a PSFeed, set username and password and traverse PSEntry objects in the feed. In theory, we’d do this:

PSClient *client = [PSClient applicationClient];
	NSURL    *url    = [NSURL URLWithString:@"https://mail.google.com/a/feed/atom/LABELNAME"];
	PSFeed   *feed   = [client feedWithURL:url];
 
	feed.login = txtEmail.stringValue;
	[feed setPassword:txtPass.stringValue];
 
	NSLog(@"Err: %@", feed.lastError);
 
	// Retrieve the entries as an unsorted enumerator
	NSEnumerator *entries = [feed entryEnumeratorSortedBy: nil];
	PSEntry *entry;
 
	// Go through each entry and get what we need
	while (entry = [entries nextObject]) {
		NSLog(@"%@", entry.summary.plainTextString);
	}

And this should work. However, it doesn’t. I always get this:

Err: Error Domain=NSURLErrorDomain Code=-1013 UserInfo=0x10017e450 "A username and password are required"

I still haven’t found the solution for this using PubSub framework. However I did manage to get the feed using plain HTTP NSConnection and simple authentication. So if anyone knows why this happens and/or knows how to solve it I would really appreciate if you notified me, thanks.

Anyway, back to our problem. Since this didn’t work, I simply tweaked it a bit and did a few things manually. I decided to use PSFeed’s initWithData:url: and pass the data (XML) manually from a NSTextField. First I opened the feed URL in my browser and logged in so I could actually see the feed. Then I opened the XML source of the feed and copied it to clipboard. Modified my GUI and added one more NSTextField which I used to paste XML feed data in and modified the Objective-C  Cocoa code like this:

	PSClient *client = [PSClient applicationClient];
	NSURL    *url    = [NSURL URLWithString:@"https://mail.google.com/mail/feed/atom/LABELNAME"];
	PSFeed   *feed   = [[[PSFeed alloc] initWithData:[txtInput.stringValue dataUsingEncoding:NSUTF8StringEncoding] URL:url] autorelease];
 
	feed.login = txtEmail.stringValue;
	[feed setPassword:txtPass.stringValue];
 
	NSLog(@"Err: %@", feed.lastError);
 
	// Retrieve the entries as an unsorted enumerator
	NSEnumerator *entries = [feed entryEnumeratorSortedBy: nil];
	PSEntry *entry;
 
	// Go through each entry and get what we need
	while (entry = [entries nextObject]) {
		NSLog(@"%@", entry.summary.plainTextString);
	}

And it finally worked fine. I parsed the feed manually and yeah, this isn’t exactly automated example but I did what I needed to do. And again, if anyone knows the solution to the authentication problem I’d love to hear it.