https://github.com/dingbat/nsrails
Railsのモデルと対になるものをiOS側で定義しておくとiOSのオブジェクトを操作するだけサーバにデータを永続化したり、データの取得ができる。ざっくりいうとparse.comと非常に使用感が似ている。
導入
導入はcocoapods経由で。Podfileにuse 'NSRails'とかくだけ。
pod 'NSRails'
iOS側でRailsアプリの場所を指定するには、AppDelegateで以下のように指定するだけ。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[NSRConfig defaultConfig].appURL = @"http://localhost:3000";
return YES;
}
Railsアプリ
アプリと適当なオブジェクト+エンドポイント一式を作っておく
rails new nsrails_test_server rails g scaffold user name:string email:string passwd:string created_at:datetime updated_at:datetime
あと、RailsアプリにCSRF対策用のキーをチェックする設定が入っているので/app/controllers/application_controller.rbのprotect_from_forgeryを:exceptionから:null_sessionに変更し無効とする。
protect_from_forgery with: :null_session
iOSアプリ
Railsのモデルに対応するモデルをクライアントとに定義する。NSRRemoteObjectを継承したクラスを作成。プロパティ名はRails側と合わせておく。
#import "NSRails.h" @interface JpPluscNSRailsTestUser : NSRRemoteObject @property (nonatomic, strong) NSString* name; @property (nonatomic, strong) NSString* email; @property (nonatomic, strong) NSString* passwd; @property (nonatomic, strong) NSString* gender; @end
iOS側のオブジェクトはプレフィックスの都合とかでRailsとあわせられない事が多いと思うので、そういう場合は実装ファイルでremoteModelName, remoteControllerNameを上書きする
+ (NSString *) remoteModelName
{
return @"user";
}
+ (NSString *) remoteControllerName
{
return @"users";
}
@end
あとはオブジェクトの作成、永続化、取得等が以下のように簡単にかける。
//オブジェクト作成、永続化
user = [[JpPluscNSRailsTestUser alloc] init];
user.name = self.aName.text;
user.email = self.aEmail.text;
user.passwd = self.aPasswd.text;
[user remoteCreateAsync:^(NSError *error) {
if (error != nil) {
NSLog(@"%@", error);
}
}];
//取得
[JpPluscNSRailsTestUser remoteAllAsync:^(NSArray *allRemote, NSError *error) {
NSMutableArray *indexPaths = [NSMutableArray array];
NSInteger size = [allRemote count];
//画面レンダリングなど...
}];
実際に書いたコード iOS
Rails
No comments :
Post a Comment