LoginSignup
6
6

More than 5 years have passed since last update.

MobileSDKを使わずにSalesforceにアクセスするiPhoneアプリを作る【API編】

Last updated at Posted at 2014-03-27

前回、OAuthの認証までを行いましたので、引き続きAPIの呼び出しをやっていきます。

StoryboardでUIの準備

例として、ChatterのFeedを取得してみます。
とりあえず、ボタン代わりにAPIを実行するためのセルと、取得したFeedを表示する為のUITableViewControllerを追加しました。

Storyboard

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の内容が取れました!

Chatter Feed

一旦access_tokenが取れてしまえば、特にライブラリ等を使用しなくてもAPIのパスさえドキュメントで見つければ、簡単にAPIを呼び出すことができます。
レスポンスの形式もリファレンスにしっかり書いてあり、Salesforce1プラットフォームの発表後はほとんどの機能がREST APIとして提供されていますので、いろんなことができます。

今回のサンプルコード全体はこちら

6
6
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
6
6