16
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iOS + Heroku(Rails / Grape)でシンプルにApi連携

Last updated at Posted at 2015-01-24

前提条件

  • ローカルでRailsプロジェクトが動く
  • HerokuにRailsプロジェクトがアップ済

Heroku側

Gemfileに追記:

Gemfile
# API
gem 'grape'

gemインストール:

$ bundle install

{プロジェクト名}/app/直下にapiフォルダを作成する。

apiフォルダのファイルを参照するようapplication.rbに記述:

application.rb
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
    config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

ルート設定:

routes.rb
mount API_v1::API => '/'

{プロジェクト名}/app/api/に以下のファイルを用意:

api_v1.rb
module API_v1
  class API < Grape::API
    version 'v1', using: :path
    format :json
    prefix :api

    # responses
    SUCCESS = 0
    FAILURE = 400
 
    helpers do
      def response(ret, obj=nil)
        if obj.nil?
          return {ret: ret}
        else
          return {ret: ret, obj: obj}
        end
      end
    end

    resource :test do
      get :rettest do
        response(SUCCESS, {foo: "bar"})
      end
    end
  end
end

以上の内容でHerokuへpush、ページを開く:

$ git add -A
$ git commit -m "Grape実装"
$ git push heroku master
$ heroku open

heroku openのURLに「/api/v1/test/rettest」を追加して叩く:

$ curl {HeokuのアプリURL}/api/v1/test/rettest
{"ret":0,"obj":{"foo":"bar"}}

JSON返ってきてるのでHeroku側はOK。

iOS側

さくっとAFNetworkingで実装する。
今回はPPNetworkManagerというファイルを用意、以下記述した:

PPNetworkManager.h
@interface PPNetworkManager : NSObject

+ (instancetype)sharedManager;
- (void)responseTest;

@end
PPNetworkManager.m
#import "PPNetworkManager.h"
#import "AFNetworking.h"

@implementation PPNetworkManager

static PPNetworkManager *sharedManager = nil;
+ (instancetype)sharedManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[PPNetworkManager alloc] init];
    });
    return sharedManager;
}

- (void)responseTest
{
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    
    // URL変更予定
    [manager GET:@"{HeokuのアプリURL}/api/v1/test/rettest"
      parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
          NSLog(@"response: %@", responseObject);
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          NSLog(@"Error: %@", error);
      }];
}

@end

あとはViewControllerなりAppDelegateなりで呼び出し:

#import "PPNetworkManager.h"

// -- 中略 -- 

[[PPNetworkManager sharedManager] responseTest];
16
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?