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

XCode 4 themes

I was searching for some cool XCode 4 themes I could use cause the default ones are pretty boring so I thought I’d share what I found with my readers.

My favorite (for now) is the Spacedust theme by m5h

Some other really interesting themes:

If you have an ‘old’ XCode 3 theme you’d like to use with XCode 4, I’m sure this will help.

Cleaning up XCode 4 user data from VCS (git)

If you use a version control system for your XCode 4 projects (and if you don’t I suggest you start) you’d probably want to keep your VCS state clean and omit committing user specific settings/files that XCode automatically creates. With XCode 3 you were probably adding *.mode1v3 and *.pbxuser files and now the .xcodeproj structure has changed so you need to modify your source control ignore files to include these new files. This simple how-to will use Git as an example but the logic applies to almost any other version control system.
XCode 4 project file now stores a special folder called “xcuserdata” amongst other folders (“xcshareddata” to name one). While xcuserdata contains user specific files that you probably want to ignore, xcshareddata contains project settings that are project specific and does not relate to users so it’s a good idea to keep that one. If you decide to delete that one, the worst thing that will happen is that you will need to recreate your project schemes. So, to keep your current build schemes pay attention to the order of the things I’m going to do.

Make your schemes “shared”

If you don’t want to lose your schemes, first you need to make them shared so you can safely ignore/delete your personal settings. To do this, go to Editor->Edit Schemes… and from the opened dialog choose “Manage Schemes”. >

XCode Edit schemes

Edit Schemes

 

Shared Scheme

Shared Scheme

Add user specific filename patterns to ignore files

Now you can ignore all those files. To do this, you simply add patterns to the .gitignore file (or your vcs of choice alternative). With Git we can do this:

echo *.mode1v3 > .gitignore
echo *.pbxuser >> .gitignore
echo *.xcuserdata >> .gitignore
echo .DS_store >> .gitignore

The first two are XCode 3 specific so if you don’t plan on using it – you can ignore these 2. The next file is XCode 4 specific and lastly I added OSX noise files as well. And that’s about it for this simple post, hope someone finds it useful.

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