AFMotionはAFNetworking
のrubymotion
用ラッパ。
お手軽に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
shared
はbuild_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