How to Post to Facebook on iOS 6 in Objective-C using ACAccountStore class

jaytrixz picture jaytrixz · Sep 20, 2012 · Viewed 36.8k times · Source

I want to know how to post a status message to Facebook on iOS 6 using the new frameworks on Xcode 4.5. Thanks! :)

Answer

Blade picture Blade · Sep 20, 2012

Posting a message is rather simple. It's almost like with the Twitter Framework.

First you have to import the Frameworks: Social and Accounts

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

In your .h file:

SLComposeViewController *mySLComposerSheet;

This code has to be included inside your action in your .m file:

    if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) //check if Facebook Account is linked
    {
      mySLComposerSheet = [[SLComposeViewController alloc] init]; //initiate the Social Controller
        mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook]; //Tell him with what social platform to use it, e.g. facebook or twitter
                [mySLComposerSheet setInitialText:[NSString stringWithFormat:@"Test",mySLComposerSheet.serviceType]]; //the message you want to post
       [mySLComposerSheet addImage:yourimage]; //an image you could post
        //for more instance methods, go here: https://developer.apple.com/documentation/social/slcomposeviewcontroller#//apple_ref/doc/uid/TP40012205
        [self presentViewController:mySLComposerSheet animated:YES completion:nil];
    }
    [mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result) {
        NSString *output;
        switch (result) {
            case SLComposeViewControllerResultCancelled:
                output = @"Action Cancelled";
                break;
            case SLComposeViewControllerResultDone:
                output = @"Post Successful";
                break;
            default:
                break;
        } //check if everything worked properly. Give out a message on the state.
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Facebook" message:output delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
    }];