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

Some XCode 4 tips

Apple kind of surprised me with releasing the XCode 4 along with the iOS 4.3. Honestly, I wasn’t expecting it until later this year or at least until iOS 5 was announced. But I’m glad it’s out, of course, and I already switched to using it vs XCode 3. I held back from trying out the beta versions so the experience was really exciting to me when I first tried it. Completely different experience compared to version 3.x and finally a single, fullscreen window. Pretty cool.

Anyway, I’m not going to review it as there are lots of reviews, I’m just going to point out a few things that I ran into while testing the last few days.

How to enable LLVM in XCode 4

By default, XCode uses a GCC kind of wrapper for LLVM so you’ll probably want to enable LLVM compiler and you can do that easily enough in build settings like so.

Now that you enabled that naturally you want to enable LLDB too. LLDB is a debugger, it’s to LLVM what GDB is to GCC. To enable LLDB you need to choose “Edit Scheme” from the “Product” menu and for the “Run” phase you’ll see a debugger chooser dropdown. However, at this point for iOS projects you’re stuck with GDB as the LLDB is only available for Mac apps and not available for iOS, yet.

How do I add existing frameworks to the XCode 4 projects?

“Add the existing framework…” right click menu option is gone. So how do you add existing frameworks?! The option is there of course, it’s just a bit hidden. The trick is to open target settings and navigate to the “Build Phases” tab. There’s a section that says “Link binary with Libraries” and that’s our X. See below.

Add existing frameworks

Add existing frameworks

So, should I switch to XCode 4?

Yup. I was in doubt and thought it might be a good idea to hold off of it for a while, at least until the next version but I tried it and found nothing that stops me from using it. In fact, I’m so pleased I’m having a hard time coding some legacy projects in XCode 3. I would suggest, though, to keep the version 3.x and install XCode 4 in a separate directory just in case…

UPDATE:

Where do I set NSZombieEnabled?

Got another tip here, it’s moved to a different place now. You need to choose “Edit Scheme” from the “Product” menu and you’ll find it there.

Edit Scheme Xcode 4

Edit Scheme Xcode 4

How to make pkg installer for Mac apps

In the previous post, I explained how to make a Mac app bundle for Java apps and in this post I’ll explain how to package apps and create Mac pkg installer for your applications. This obviously applies to non-Java apps as well hence the generalized title.

The only tool we’ll need for this is ‘Package Maker’ app that comes with Mac development tools bundle.

Package Maker

Package Maker

If you’re in a hurry and don’t care much about the details, you just drag & drop the files you want installed (your .app, images, docs etc…) into the left sidebar and fill in the basic fields (app title, installer description) and you’re good to go. However, this little app holds much more advanced options and if you care to dig in a little bit you’ll find much more options for customizing your app setup process. Below are the few examples but there is, of course, a lot more.

Although this post doesn’t look like a step-by-step how-to, if you just need a way to package your app without much trouble you just point ‘n’ shoot and you’re done. I might explain the advanced options some time in the future though.

How to create Mac OS app bundle for Java apps

Java apps work great on our Macs, JAR bundles are recognized “out of the box” and launched as executable files automatically by the operating system. But we always want more and we want to be as native as possible so naturally we would like to package our JAR’s into .app bundles to give them more Mac look & feel. In this post I’ll explain how to easily create Mac app bundles out of your Java app JAR’s using Mac OS development tools.

Preps

We’ll need a few things to begin with and those are the JAR file(s) you’re bundling and the app icons. Icons need to be in Mac OS .icns format and there’s a nice tool that will create this for you and it’s called “Icon Composer”. Icon composer (as well as other tools I’ll mention in this post) is installed along with Mac OS development tools from Apple’s website.

Using Icon Composer to create .icns is pretty straight-forward process. You will just need a 512×512 PNG of your icon and you just drag & drop it into the Icon Composer and save as .icns.

Icon Composer

Icon Composer

Bundling Mac OS app

The thing to do is to actually create a Mac OS .app bundle from you JAR file(s) using “JAR bundler” tool (comes along with Mac OS development tools). The app interface is simple enough – you get to choose your JAR executable and specify main class and you’re good to go. There’s, of course, more options if you want to include additional jar’s or files and to specify basic properties for your Java app.

JAR bundler

JAR bundler

Now if you have a single JAR file you shouldn’t have any problems. However, if your JAR file depends on some external libraries, images etc. you might have troubles with dependency file paths. I did. I had a subfolders “lib” and “images” full of external libraries and images my app was using. I tried to solve it ‘their’ way by trying to fix the paths but it took a long time and I couldn’t get it working so I found a much quicker workaround I want to share here.

Instead of having multiple JAR files and additional dependencies, I decided to end the nightmare of handling file paths by bundling everything into one single JAR file. And directly from NetBeans too. There’s a well documented tutorial here. Basically, you need to put the code below in your build.xml file and choose target package-for-store when building your app and a single JAR will be created for you.

<target name="package-for-store" depends="jar">
 
        <!-- Change the value of this property to be the name of your JAR,
             minus the .jar extension. It should not have spaces.
             <property name="store.jar.name" value="MyJarName"/>
        -->
        <property name="store.jar.name" value="MyJarName"/>
 
        <!-- don't edit below this line -->
 
        <property name="store.dir" value="store"/>
        <property name="store.jar" value="${store.dir}/${store.jar.name}.jar"/>
 
        <echo message="Packaging ${application.title} into a single JAR at ${store.jar}"/>
 
        <delete dir="${store.dir}"/>
        <mkdir dir="${store.dir}"/>
 
        <jar destfile="${store.dir}/temp_final.jar" filesetmanifest="skip">
            <zipgroupfileset dir="dist" includes="*.jar"/>
            <zipgroupfileset dir="dist/lib" includes="*.jar"/>
 
            <manifest>
                <attribute name="Main-Class" value="${main.class}"/>
            </manifest>
        </jar>
 
        <zip destfile="${store.jar}">
            <zipfileset src="${store.dir}/temp_final.jar"
            excludes="META-INF/*.SF, META-INF/*.DSA, META-INF/*.RSA"/>
        </zip>
 
        <delete file="${store.dir}/temp_final.jar"/>
 
    </target>

Now all you need to do is to use this JAR file with JAR bundler and you’ll have a Mac OS .app in no time ready to send to your users.

In the next post, I’ll write how to use this Mac OS .app to create an installer for your app. Until then, stay tuned!

Reusing code with Snippets for Mac

I was never a fan of any snippets tools for development, it may be because I never came across any descent app and maybe I didn’t even need one. One thing is sure, while coding, I always have several projects opened and I’m copy/pasting code like crazy all over them. So I guess I do need one after all. Recently I stumbled upon a very nice app called Snippets for Mac and I decided to give it a try.

What I need from this kind of app is:

  1. to integrate nicely with my Mac OSX desktop
  2. have a clean and nice GUI
  3. provide the best user experience

These are 3 most important features I need and the last one is crucial. Snippets app manages to get good ratings here. Snippets app does everything you’d expect from this kind of app: searching, syncing, easy access etc..

Snippets app has a very slick interface as you would expect from a modern Mac OSX app. Main window has a library tree view, along with the highlights and groups on the left and code editor on the right. GUI is pretty much straight-forward and you can easily add new snippets or select existing ones.

Snippets Main Window

Snippets app main window

Editing snippets is just as easy and what I like about it is that you can use different editors launching from within the app. From toolbar, you can choose whether you want to edit the snippet in XCode, Coda, TextEdit or other editors of your choice.

Choose editor for a snippet

Choose editor for a snippet

Now, ‘integration’ with the actual editors/IDEs where one does coding is the most important part. This is where snippets bought me. While it doesn’t integrate with IDEs per se (you can easily copy code from its main window), it’s much easier and quicker to do it from the tray icon either by clicking on it or using a global shortcut which is quicker and you can insert a snippet without loosing focus in your code editor. Either by clicking the tray icon or using a global shortcut,  you quickly get a list of search results and you can add the code momentarily.

Adding snippets

Inserting snippets

Another great feature is that highlighting a search result shows a tooltip with the code that snippet holds. This is very useful because sometimes I name snippets similarly or even forget what it has.

The app does satisfy my needs as a simple snippet manager and provides me simpler way of reusing my code than to browse around my old projects and copy/pasting code. I’m still in my trial period and deciding whether or not this software is worth the money ($39,95 at the moment, comes with 30 day trial) but it is being useful no doubt about it. I suggest you take it for a spin and see if it fits you.

Snippets website / download

Snippets for Mac