JSONによるWEBアプリとiPhoneアプリのAPI連携
RailsアプリケーションでJSONデータを返すAPIを実装し、iPhoneアプリから受信する方法をご紹介します。
iPhoneアプリ
json-framworkというフレームワークを使ってJSONを扱うことができます。
- json-framework をiPhoneSDKに組み込む
$HOME/Library/SDKs/JSON/$(PLATFORM_NAME).sdk
-
-
- 「ビルド」=>「他のリンカフラグ」の値に以下を記述します。
-
-ObjC -ljson -all_load
-
-
-
- 私の環境では、シミュレータでは再現せず実機でのみクラッシュするバグが起きたため、 -all_load も追記しました。
-
-
#import "JSON/JSON.h"
-
- 受け皿の実装
// JSONデータのリクエスト NSURL *jsonURL = [NSURL URLWithString:@"http://0.0.0.0:3000/users/show/1.json"]; NSMutableString *jsonData = [NSMutableString stringWithContentsOfURL:jsonURL encoding:NSUTF8StringEncoding error:nil]; // シングルクォーテーションはJSONでは扱えないため、ダブルクォーテーションに変換 [jsonData replaceOccurrencesOfString:@"'" withString:@"\"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[jsonData length])]; // result にデータを受けて出力 if (jsonData != nil) { id result = [jsonData JSONValue]; // JSONValue が外部メソッド NSLog(@"%@", result); }
Railsアプリケーション
# config/routes.rb map.connect ':controller/:action.:format' map.connect ':controller/:action/:id.:format' # users/show/1 のようにパラメータをパスで扱っている場合
- アクションからJSONデータを返す
render :text => @object.to_json
$ ruby script/console Loading development environment. >> data = {"id" => 1} => {"id"=>1} >> data.to_json => "{id: 1}" # 属性がダブルクォートされていない >> require "json" => ["JSON"] >> data.to_json => "{\"id\":1}" # 属性がダブルクォートされている
require "json" ・・・ render :text => @object.to_json