iPhone Development: Post to Facebook and Twitter using SLComposeViewController

Post image and text to social network is a common feature used in all iPhone/iPad apps. We can post image and text using different techniques in iPhone. One of them is SLComposeViewController.

The SLComposeViewController class presents a view to the user to compose a post for supported social networking services.
First we will check for the availability of class i.e wether it is present to use
if (!NSStringFromClass([SLComposeViewController class])) {
        [[[[UIAlertView alloc] initWithTitle:@”Sorry” message:@”This feature is available in later version. Please update your device for this feature.” delegate:nil cancelButtonTitle:@”OK” otherButtonTitles:nil] autorelease] show];
    }
If class is available to use, we will use it and present a native sheet otherwise will show alert to user that this functionality is not available for the current IOS installed on their device. Then we will check wether user is logged-in for particular service in settings app. If not then display alert that you are not logged-in, otherwise will display our posting or default sheet with tittle or image whatever we want to post.And finally will display alert as per the response we got in completion handler.
Below is the code  for posting image or text to Facebook and twitter.
 if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {
        SLComposeViewController *compose = [SLComposeViewController composeViewControllerForServiceType: SLServiceTypeTwitter];
        [compose setInitialText:postText];
        [compose addImage:[UIImage imageNamed:@”aman.png”]];
        [self.navigationController presentViewController:compose animated:YES completion:NULL]; 
        [compose setCompletionHandler:^(SLComposeViewControllerResult result) {
            [compose dismissViewControllerAnimated:YES completion:NULL];
            switch (result) {
                case SLComposeViewControllerResultCancelled:
                    break;
                case SLComposeViewControllerResultDone:
                    [[[[UIAlertView alloc] initWithTitle:@”Sharing..” message:@”Post is being shared in background” delegate:nil cancelButtonTitle:@”OK” otherButtonTitles:nil] autorelease] show];
                    break;
                    
                default:
                    break;
            }
        }];
        
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”Not Logged In” message:@”You have not set up account in device for this service type. Go to setting, login and post again” delegate:nil cancelButtonTitle:@”OK” otherButtonTitles:nil];
        [alertView show];
        [alertView release];
        alertView = nil;
    }  


NOTE:- in above code i used twitter service, to post to facebook replace SLServiceTypeTwitter with SLServiceTypeFacebook.