[iOS]Tweeting(アカウント管理) | Cocoa練習帳

[iOS]Tweeting(アカウント管理)

独自にOAuth/xAuthに対応する場合は、アプリケーションはアカウントに対応したアクセストークンを取得して、これを使ってアクセスすることになる。


iOS5から用意されたTwitter/Accounts frameworkを利用する場合、そもそも管理されているTwitterアカウントが複数あり、ユーザがそれのどれを選択したのか管理する必要がある。


それが、ACAccountのプロパティidentifierだ。




- (IBAction)tweet2:(id)sender
{
    ACAccountStore *accountStore = [[ACAccountStore alloc] init];

    ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [accountStore requestAccessToAccountsWithType:accountType
            withCompletionHandler:^(BOOL granted, NSError *error) {
        if(granted) {
            NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];

            for (NSUInteger i = 0; i < [accountsArray count]; i++) {
                ACAccount *twitterAccount = [accountsArray objectAtIndex:i];
                NSLog(@"account: %@", twitterAccount);

                TWRequest *postRequest = [[TWRequest alloc]
                    initWithURL:
                    [NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"]
                    parameters:[NSDictionary dictionaryWithObject:@"hello, world" forKey:@"status"]
                    requestMethod:TWRequestMethodPOST];

                [postRequest setAccount:twitterAccount];
                
                NSLog(@"credential: %@", twitterAccount.credential);
                NSLog(@"identifier: %@", twitterAccount.identifier);

                [postRequest performRequestWithHandler:
                        ^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
                    NSString *output = [NSString stringWithFormat:@"HTTP response status: %i",
                        [urlResponse statusCode]];
                    NSLog(@"%@", output);
                    [self performSelectorOnMainThread:@selector(displayText:)
                        withObject:output waitUntilDone:NO];
                }];
            }
        }

}



ACAccountのプロパティidentifierを保存しておけば、ACAccountStoreクラスの - (ACAccount *)accountWithIdentifier:(NSString *)identifier メソッドを使えば、ACAcountクラスのインスタンスを得られる。




ソースコード
GitHubからどうぞ。

https://github.com/murakami/workbook/tree/master/ios/Tweets - GitHub


関連情報
iOS Twitter framework

Twitter Developersサイトの情報。

Tweeting

Developerサイトのサンプル・コード