77

What are the steps I need to follow to use iOS 6's new SLComposeViewController to post to Facebook, Twitter or Sina Weibo?

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281

3 Answers3

141

For details on this framework please see Apple's Social Framework Class Reference

Additional tutorials:

  1. http://soulwithmobiletechnology.blogspot.com/2012/07/tutorial-how-to-use-inbuilt.html
  2. http://www.mobile.safilsunny.com/iphone/integrating-facebook-ios/
  3. https://rudeboy-quickies.blogspot.com/2012/06/steps-to-integrate-facebook-in-ios6.html

For this example, we will be using the SLComposeViewController's SLServiceTypeFacebook. If you wish to use Twitter or SinaWeibo just change out the SLServiceType to one of the following:

  • SLServiceTypeFacebook
  • SLServiceTypeSinaWeibo
  • SLServiceTypeTwitter

iOS 6 has made it very easy to post directly to Facebook, Twitter or Sina Weibo using the SLComposeViewController. This works very similarly to iOS 5's TWTweetComposeViewController.

First, in your view controller's header file (.h) #import the Social Framework and the Accounts Framework.

#import <Social/Social.h>

#import <Accounts/Accounts.h>

Here we will declare a simple UIButton and an IBAction that we will later link to that button and a void (sharingStatus) which will be used to check that the selected sharing service is available.

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIButton *easyFacebookButton;
- (IBAction)facebookPost:(id)sender;
- (void)sharingStatus;
@end

@implementation ViewController

Then, in your implementation file (.m), we'll start by implementing the (sharingStatus) void that we declared in the header file. sharingStatus uses SLComposeViewController's isAvailableForServiceType BOOL to return whether or not you can post to the service specified in its argument. In this case, we will use the service type SLServiceTypeFacebook. If the service is available the post button will be enabled with an alpha value of 1.0f, and if the service isn't available the button will be disabled its alpha value set to 0.5f.

- (void)sharingStatus {
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
        NSLog(@"service available");
        self.easyFacebookButton.enabled = YES;
        self.easyFacebookButton.alpha = 1.0f;
    } else {
        self.easyFacebookButton.enabled = NO;
        self.easyFacebookButton.alpha = 0.5f;
    }
}

Here we will set up the IBAction that will call up the composer. For good practice, we will check isAvailableForServiceType again to avoid calling up the composer for a service type that isn't available. (Incase something went wrong during the last check, or if availability somehow changed in the fraction of a second in between tapping the post button and the composers all/init. The code below has been set up to display a Facebook composers sheet with text, an image, and a link. This action also utilises a completion handler for the composer's cancelled and done results.

- (IBAction)facebookPost:(id)sender {

    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {

        SLComposeViewController *mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

        [mySLComposerSheet setInitialText:@"iOS 6 Social Framework test!"];

        [mySLComposerSheet addImage:[UIImage imageNamed:@"myImage.png"]];

        [mySLComposerSheet addURL:[NSURL URLWithString:@"http://stackoverflow.com/questions/12503287/tutorial-for-slcomposeviewcontroller-sharing"]];

        [mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result) {

             switch (result) {
                 case SLComposeViewControllerResultCancelled:
                     NSLog(@"Post Canceled");
                     break;
                 case SLComposeViewControllerResultDone:
                     NSLog(@"Post Sucessful");
                     break;

                 default:
                     break;
             }
         }];

        [self presentViewController:mySLComposerSheet animated:YES completion:nil];
    }
}

In viewWillAppear we will register an observer to ACAccountStoreDidChangeNotification so the application can be notified when account information changes. This observer will then be removed in viewDidDisappear.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sharingStatus) name:ACAccountStoreDidChangeNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:ACAccountStoreDidChangeNotification];
}

And finally, open up interface builder and add a UIButton which will be the post button. Then in the connections inspector link the IBOutlet and IBAction we created earlier to the button, and that's it! You're done!

enter image description here

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
  • 1
    Hi, It was a nice answer,though i have small doubt,can we also present Login interface in case user's twitter/Facebook account is not set up? – Abhinandan Sahgal Dec 31 '12 at 05:42
  • 3
    @AbhinandanSahgal no, not with this class. However, when working properly the composer will detect if the user isn't logged in and present an alert to take them to the settings for the appropriate service to log in to their account. – Mick MacCallum Dec 31 '12 at 07:02
  • Can you put a sample to take them to settings? – Abhinandan Sahgal Dec 31 '12 at 07:14
  • 1
    @AbhinandanSahgal Sorry, but no I can't. This is build in behavior that should be working automatically if you aren't already logged in. Additionally, Apple used to offer API for sending the user to the preferences app, but it was removed in iOS 5.1 :( – Mick MacCallum Dec 31 '12 at 15:05
  • 7
    There's no need to link to Accounts.framework when using Social.framework. Also it can be a disadvantage to check if a service is available since the OS will do this automatically and fail with an alert that has a Settings button. – martinjbaker Mar 13 '13 at 12:23
  • 1
    Don't do the [SLComposeViewController isAvailableForServiceType:...] check and if that service is not set up in the Settings app, the framework will popup an alert stating that issue along with a button to go into settings. – Surpher Aug 20 '14 at 04:34
  • how to hide location and audience option from this pop up? – Monika Patel Sep 16 '15 at 04:54
  • @0x7fffffff why image is not getting upload in this code ? – Kishore Kumar Jan 27 '16 at 09:52
  • In **iOS 11**, remove this line: `if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {` – Matheus Domingos Oct 04 '17 at 14:09
25

Just use this code to share on Facebook.

SLComposeViewController *controllerSLC = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[controllerSLC setInitialText:@"First post from my iPhone app"];
[controllerSLC addURL:[NSURL URLWithString:@"http://www.appcoda.com"]];
[controllerSLC addImage:[UIImage imageNamed:@"test.jpg"]];
[self presentViewController:controllerSLC animated:YES completion:Nil];

If you want this for Twitter then just change SLServiceTypeTwitter.

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
Desert Rose
  • 3,376
  • 1
  • 30
  • 36
13

Safe Use of SLComposeViewController

if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
    {
        SLComposeViewController *fbPost = [SLComposeViewController
                                               composeViewControllerForServiceType: SLServiceTypeFacebook];
        [fbPost setInitialText:@"Text You want to Share"];
        [fbPost addImage:[UIImage imageNamed:@"shareImage.png"]];
        [self presentViewController:fbPost animated:YES completion:nil];
        [fbPost setCompletionHandler:^(SLComposeViewControllerResult result) {
            switch (result) {
                case SLComposeViewControllerResultCancelled:
                    NSLog(@"Post Canceled");
                    break;
                case SLComposeViewControllerResultDone:
                    NSLog(@"Post Sucessful");
                    break;
                default:
                    break;
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
    }
Meet Doshi
  • 4,241
  • 10
  • 40
  • 81
A R
  • 461
  • 4
  • 14