Objective-C (iOS): ツイート

TweetViewController`

Social.framework をプロジェクトに追加します。

Objective-C: TweetViewController.h

#import <UIKit/UIKit.h>
#import <Social/Social.h>

@interface TweetViewController : UIViewController

@end

Objective-C: TweetViewController.m

#import "TweetViewController.h"

@interface TweetViewController ()

@end

@implementation TweetViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(20,20,150, 50);
    [button setTitle:@"Tweet" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(tweetButtonWasTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)tweetButtonWasTapped
{
    SLComposeViewController *tweetView = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
    [tweetView setInitialText:@"デフォルト文言"];
    // URL をシェアする場合
    // NSURL *url = [NSURL URLWithString:@"http://feb19.jp/"];
    // [tweetView addURL:url];
    
    [tweetView setCompletionHandler:^(SLComposeViewControllerResult result) {
        switch (result) {
            case SLComposeViewControllerResultCancelled:
                // キャンセルボタンが押された
                break;
            case SLComposeViewControllerResultDone:
                // ツイートが完了した
                break;
            default:
                break;
        }
        
        // 消す
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    // 出す
    [self presentViewController:tweetView animated:YES completion:nil];
}

@end