LoginSignup
9
9

More than 5 years have passed since last update.

iOS5以上対応アプリにTwitterでの投稿機能を付けたときのメモ。
iOS6からはsocial.frameworkを使うと、TwitterとかFacebook周りの実装ができるらしい。
今回はiOS5にも対応する必要があるのでTwitter.frameworkを使う。

ちなみに、投稿だけなら、TWTweetComposeViewControllerクラスを使うと簡単にできる。ただ、今回は、Twitterの投稿画面を表示したくなかったので、TWRequestを用いて実装した。

必要なフレームワーク

・Twitter.framework
  当然必要。
・Accounts.framework
  アカウントの管理に必要。

Twitterアカウントへのアクセス権の取得

---略---
#import <Accounts/Accounts.h>
#import <Twitter/Twitter.h>
---略---

ACAccountStore *store = [[ACAccountStore alloc] init];
ACAccountType *twitterType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    [store requestAccessToAccountsWithType:twitterType
                     withCompletionHandler:^(BOOL granted, NSError *error) {
                         if (granted) {
                             //アクセスが許可されたときの処理
                             //設定されているアカウントを取得
                             self.twitterAccounts = [store accountsWithAccountType:twitterType]; 
                         }else {
                             //アクセスが拒否されたときの処理
                         }
                     }];

初回アクセスのときはアクセス許可を求めるダイアログが表示される。

取得したアカウントでツイート

//Twitter APIのURL(今回はツイート投稿なので、POST statuses/update)
NSURL *postUrl = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/update.json"];
//必要なパラメータ
NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"投稿する文" forKey:@"status"];
TWRequest *postRequest = [[TWRequest alloc] initWithURL:postUrl
                                             parameters:parameters
                                          requestMethod:TWRequestMethodPOST];

//上で取得したアカウントをセット
ACAccount *twitterAccount = [twitterAccounts objectAtIndex:0]; 
postRequest.account = twitterAccount;

//投稿    
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        //投稿完了時の処理
    });
}];

APIのURLや必要なパラメータはTwitter APIの公式ドキュメントを参照。

参照

加藤寛人, 吉田悠一, 藤川宏之, 西方夏子, 関川雄介, 高丘知央 著 『iOS5プログラミングブック』初版

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