LoginSignup
2
2

More than 5 years have passed since last update.

AFMotionでWeb APIを実行する。

Posted at

AFMotionAFNetworkingrubymotion用ラッパ。
お手軽にAPIを使えるのが良さげ。試しにQiitaのAPIを実行してみる。

インストール

bundle init
Gemfile
gem 'afmotion'
bundle install
Rakefile
require 'bundler'
Bundler.require

Motion::Project::App.setup do |app|
  app.name = 'hoge'
  app.pods do
    pod 'AFNetworking'
  end
end

設定

APIのベースとなるURL、およびやり取りにJSONを使うことを指定。

AFMotion::Client.build_shared('https://qiita.com/api/v1') do
  header "Accept", "application/json"
  operation :json
end

実行

検索を実行してみる。

AFMotion::Client.shared.get('search', {'q' => 'ruby'}) do |result|
  if result.success?
    p result.content
  elsif result.failure?
    p result.error.localizedDescription
  end
end

sharedbuild_sharedで指定されたURLをベースとして対象のURLを構築して実行する。
この場合、https://qiita.com/api/v1/search?q=rubyが対象のURLとなる。

result.contentの形式はoperationで指定した値によって変化する。詳細は下表の通り。

operation 結果の形式
json Hash, Array
PLIST Hash, Array
XML NSXMLParser
HTTP NSURLResponse

おまけ

画像を表示する

@image = UIImageView.alloc.initWithFrame([[10, 100], [160,160]]).tap do |v|
  v.url = 'http://hoge/fuga.jpg'
end
2
2
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
2
2