前回、OAuthの認証までを行いましたので、引き続きAPIの呼び出しをやっていきます。
StoryboardでUIの準備
例として、ChatterのFeedを取得してみます。
とりあえず、ボタン代わりにAPIを実行するためのセルと、取得したFeedを表示する為のUITableViewControllerを追加しました。
Chatter REST APIでFeedを取得する
とりあえず簡単にviewDidLoad
で/chatter/feeds/people/me/feed-items
のAPIを使用して自分のFeedを取得してみます。
Chatter REST APIのドキュメントはここ
SEChatterFeedViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// 取得済みの認証情報からaccess_tokenとinstance_url
NSString *accessToken = _authInfo[@"access_token"];
NSString *instanceURL = _authInfo[@"instance_url"];
// access_tokenをAuthorizationヘッダにセット
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPAdditionalHeaders = @{@"Authorization": [NSString stringWithFormat:@"Bearer %@", accessToken]};
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 呼び出すAPIのURL
NSString *url = [instanceURL stringByAppendingPathComponent:@"/services/data/v29.0/chatter/feeds/people/me/feed-items"];
// ChatterのFeedをAPIで取得
NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
if (error) {
// エラー表示
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:error.localizedDescription delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
[alert show];
} else {
// 取得したFeedItem配列をセットしてテーブル再表示
NSDictionary *feedItemPage = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
_feeditems = feedItemPage[@"items"];
[self.tableView reloadData];
}
}];
}];
[task resume];
}
取得したFeedItemの、actor/name
に投稿者の名前、body/text
に投稿本文が含まれているので、これらを表示します。
SEChatterFeedViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSDictionary *feeditem = _feeditems[indexPath.row];
cell.textLabel.text = feeditem[@"actor"][@"name"];
cell.detailTextLabel.text = feeditem[@"body"][@"text"];
return cell;
}
実行してみる
実行してみると、こんな感じでFeedの内容が取れました!
一旦access_tokenが取れてしまえば、特にライブラリ等を使用しなくてもAPIのパスさえドキュメントで見つければ、簡単にAPIを呼び出すことができます。
レスポンスの形式もリファレンスにしっかり書いてあり、Salesforce1プラットフォームの発表後はほとんどの機能がREST APIとして提供されていますので、いろんなことができます。