Técnico

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

@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

#import "User.h"

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

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


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

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

You can use http basic auth as well:


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

Now its easy to get your users:


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 ?

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Compartilhe isso: