How to post to Facebook and Twitter using Social Framework

It is extremely simple to bring up Facebook and Twitter Sheets in your app using the Social Framework.

Once imported you can create a new instance of SLComposeViewController, initialise it with text, an image and a URL, and present it modally from your own view controller.

Screen Shot 2013-12-06 at 18.50.57

You don’t have to specify anything other than which service you’d like to use, in which case the presented sheet will be blank. Here we bring up a tweet sheet (i.e. Post to Twitter dialogue):

- (IBAction)socialSheet:(id)sender {

    // create Twitter controller
    SLComposeViewController *socialController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];

    // present controller
    [self presentViewController:socialController animated:YES completion:nil];
}

And here we specify all three values for a post to Facebook:

- (IBAction)socialSheet:(id)sender {

    // create Facebook controller
    SLComposeViewController *socialController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

    // add initial text
    [socialController setInitialText:@"Hello Facebook!"];

    // add an image
    [socialController addImage:[UIImage imageNamed:@"picture.jpg"]];

    // add a URL
    [socialController addURL:[NSURL URLWithString:@"http://wpguru.co.uk"]];

    // present controller
    [self presentViewController:socialController animated:YES completion:nil];
}

Available service types are

– SLServiceTypeFacebook
– SLServiceTypeTwitter
– SLServiceTypeSinaWeibo
– SLServiceTypeTencentWeibo

You can test if a service is available using the isAvailableForService method (which always returns YES on the simulator, and only gives accurate results on a real device):

if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {

    // show Twitter option
}




Leave a Reply