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

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

iOS5からのTwitter/Accounts frameworkの凄いところは、複数のアカウントを扱える事だ。DeveloperサイトのサンプルコードTweetingのコードに手を加えて、iOS機器に登録されているアカウントの全てでtweetするようにしてみた。





- (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];

                [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];
                }];
            }
        }

}



登録されているアカウント分、同じ内容のtweetが投稿されている事が確認できると思う。無意味な内容なので迷惑だと思うが。






ソースコード

GitHubからどうぞ。

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




関連情報

iOS Twitter framework

Twitter Developersサイトの情報。

Tweeting

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