Cocos2d-xとTwitter Kitを使ってOAuth認証&ユーザタイムライン取得-iOS編その2

Cocos2d-xとTwitter Kitを使ってOAuth認証&ユーザタイムライン取得-iOS編その1の続き。
前回Twitterにログインしたので、今回はシングルツイートの取得とユーザタイムラインの取得をします。

シングルツイートの取得


std::string NativeLauncher::showTweet(){
    NSURLRequest *request = [[[Twitter sharedInstance] APIClient] URLRequestWithMethod:@"GET"
URL:@"https://api.twitter.com/1.1/statuses/show.json"
parameters:@{@"id":@"xxxxxxxxxxxxxxxxxx"}
error:nil];
    NSURLResponse *response;
    NSError *err;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
    std::string tweet_text = [[jsonObject valueForKey:@"text"] UTF8String];
    return tweet_text;
};

xxxxxxxxxxとなっている所にツイートIDを入れてください。
NSDataが帰ってくるので、NSJSONSerializationでNSDictionaryに変換します。
valueForKeyの"text"のところを変えると他の情報も取得できます。
他のパラメータや、データの構造は、GET statuses/show/:idを見てください。
非同期では無く同期で呼び出したかったので、sendSynchronousRequestを使いました。

ユーザタイムラインの取得


std::vector<std::string> NativeLauncher::showUserTimeline(){
    NSURLRequest *request = [[[Twitter sharedInstance] APIClient] URLRequestWithMethod:@"GET"
URL:@"https://api.twitter.com/1.1/statuses/user_timeline.json"
parameters:@{@"count":@"10"}
error:nil];
    
    NSError *err;
    NSURLResponse *respon;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&respon error:&err];
    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
    std::vector<std::string> userTimeline_text;
    for (NSDictionary* tweet in jsonObject) {
        userTimeline_text.push_back([[tweet valueForKey:@"text"] UTF8String]);
    }
    return userTimeline_text;
};

ほとんど同じですが、タイムラインなので、forを使って一つづつ取り出しています。
URLの最後の部分を変えれば他の情報も取り出せます。
詳しくはREST APIsを見てください。

コメント

このブログの人気の投稿

2次元配列のコピー::JavaScript

iframeの利点と欠点

chromyを実行するとエラー:"Failed to launch a browser"が出る