Thursday, May 29, 2014

Simple way to Share Images from iOS App to Facebook and Twitter - One method for both

sharing Image in social sites (Facebook and Twitter)....first import social,facebook,twitter frameworks


/To share the final image on twitter
-(void)shareImageToTwitter
{
    [self shareImage:savedImage withText:nil onSocialSite:SLServiceTypeTwitter];
}

//To share the final image on facebook
- (void)shareImageToFacebook
{
    [self shareImage:savedImage withText:nil onSocialSite:SLServiceTypeFacebook];
}

here "savedImage " was sharing image


//Common method to share image on twitter & facebook
-(void)shareImage :(UIImage *)postImage withText :(NSString *)message onSocialSite :(NSString *const )socialSiteType
{
    SLComposeViewController *socialSiteComposer=[SLComposeViewController composeViewControllerForServiceType:socialSiteType];
    if([SLComposeViewController isAvailableForServiceType:socialSiteType])
    {
        SLComposeViewControllerCompletionHandler __block completionHandler=^(SLComposeViewControllerResult result){
           
            [socialSiteComposer dismissViewControllerAnimated:YES completion:nil];
           
            switch(result)
            {
                case SLComposeViewControllerResultCancelled:
                default:
                {
                    NSLog(@"Cancelled.....");
                }
                    break;
                case SLComposeViewControllerResultDone:
                {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"Posted successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [alertView show];
                }
                    break;
            }};

        //Add content to post
        [socialSiteComposer setInitialText: message];
        NSData *data = UIImageJPEGRepresentation(postImage, 1.0);
        [socialSiteComposer addImage:[UIImage imageWithData:data]];
       
        [socialSiteComposer setCompletionHandler:completionHandler];
        [self presentViewController:socialSiteComposer animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Sorry!" message:@"You can't post right now, make sure you have at least one account setup" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}