Objective-C (iOS): Facebook でシェア

FacebookShareViewController

Social.framework を Optional でリンクしておきます。
※Optional ではなく Required だと iOS5 でアプリが起動しなくなってしまいます。

Objective-C: FacebookShareViewController.h

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

@interface FacebookShareViewController : UIViewController

@end

Objective-C: FacebookShareViewController.m

#import "FacebookShareViewController.h"

@interface FacebookShareViewController ()

@end

@implementation FacebookShareViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImage *image = [UIImage imageNamed:@"snippets_feb19_jp"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = self.view.bounds;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:imageView];
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(50, 50, 150, 50);
    [button setTitle:@"シェア" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonWasTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)buttonWasTapped:(UIButton *)button
{
    [self sendFacebook:[UIImage imageNamed:@"snippets_feb19_jp"] title:@"THE_PROGRAMING_TIPS_AND_CODING_MEMOS" url:@"http://snippets.feb19.jp"];
}

- (NSString *)encode:(NSString *)string
{
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                         NULL,
                                         (CFStringRef)string,
                                         NULL,
                                         (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                         kCFStringEncodingUTF8));
}

- (void)sendFacebook:(UIImage *)image title:(NSString *)title url:(NSString *)urlString
{
    if(NSClassFromString(@"SLComposeViewController")) {
        
        SLComposeViewController *composeViewController = [SLComposeViewController
                                                          composeViewControllerForServiceType:SLServiceTypeFacebook];
        [composeViewController setInitialText:[NSString stringWithFormat:@"%@\n%@", title, urlString]];
        [composeViewController addImage:image];
        [self.navigationController presentViewController:composeViewController
                                                animated:YES
                                              completion:nil];
    } else {
        // iOS 5 以下はブラウザに移動してシェア機能を起動する
        NSString *escapedMessage = [self encode:title];
        NSString *escapedUrlString = [self encode:urlString];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.facebook.com/sharer.php?u=%@&t=%@", escapedUrlString, escapedMessage]]];
        
    }
}

@end