29 set 2010

Consuming Rails webservices with ObjectiveResource

I’ve been studying ruby and objective-c for a while and found the ObjectiveResource project very interesting. Actually, its a good way to start developing some app for iphone consuming your rails RESTful (no hateoas) webservices without worrying (so much) about objects serialization or to use JSON/XML with NSDictionaries at your view controllers.

They have a great screencast for starters and there’s a objectiveresource group that will answer your doubts asap.

Quick start

Assuming you have REST webservices for some User domain at your Rails app and have imported the ObjectiveResource API to your xcode project, create an objective-c interface and implementation for User:

User.h

1
2
3
4
5
6
7
8
9
10
@interface User : NSObject {
    NSNumber *userId;
    NSString *name;
    NSString *email;
}

@property (nonatomic, retain) NSNumber *userId;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *email;
@end

User.m

1
2
3
4
5
#import "User.h"

@implementation User
@synthesize userId, name, email;
@end

Configure ObjectiveResource at applicationDidFinishLaunching method from AppDelegate using the ObjectiveResourceConfig class method setSite:

1
[ObjectiveResourceConfig setSite:@"http://localhost:3000"];

The response type can be defined using setResponseType: XmlResponse | JSONResponse.

You can use http basic auth as well:

1
2
[ObjectiveResourceConfig setUser:@"brunofuster"];
[ObjectiveResourceConfig setPassword:@"brunofuster"];

Now its easy to get your users:

1
2
3
4
5
6
import "ObjectiveResource.h"
...
-(NSArray) getUsers {
  NSArray *users = [User findAllRemote];
  return users;
}

This will consume /users.json|xml and serialize the response into an array of fresh new User objects.

There are methods for CRUD operations like saveRemote, destroyRemote, updateRemote and findRemote (based on ActiveResource), although you can create your own calls like “search_users_nearby” (check the getting started tutorial).

Important: ObjectiveResource calls aren’t async. You should use ConnectionManager (branch 1.1 at github). Check a sample at http://gist.github.com/66593

Quite interesting, uh ?

Leave a Comment