iLounge | All Things iPod, iPhone, iPad and Beyond

Friday 10 August 2012

Iphone Facebook Sharings using objective c

Firstly,download facebook sdk for iphone from here

next,drag & drop this sdk folder into your xcode project. has to look like above screen shot.

import Facebook.h class in FbSharingownViewController.h file

//FbSharingownViewController.h

#import <UIKit/UIKit.h>
#import "Facebook.h"

@interface FbSharingownViewController : UIViewController<FBSessionDelegate,FBRequestDelegate>
{
    Facebook *facebook;
    BOOL ISFBCONNECTED;
    NSArray *permissions;
    UIView *v;
    UIProgressView *prog;
    UIButton *but,*but1,*but2,*but3,*but4;
    UIButton *UploadCancel;
}
@property(nonatomic,retain)Facebook *facebook;
@property(nonatomic)BOOL ISFBCONNECTED;
@end



//FbSharingownViewController.m






#import "FbSharingownViewController.h"

@interface FbSharingownViewController ()

@end

@implementation FbSharingownViewController
@synthesize facebook;
@synthesize ISFBCONNECTED;
- (void)viewDidLoad
{
    [super viewDidLoad];
   
 
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 480, 320)];
    [imageView setImage:[UIImage imageNamed:@"social-networking-625x450.jpeg"]];
    [self.view addSubview:imageView];
    but1=[[UIButton alloc]init];
    but1=[UIButton buttonWithType:UIButtonTypeCustom];
    but1.backgroundColor=[UIColor colorWithRed:0.0 green:0.0 blue:0.5 alpha:0.6];
    but1.frame=CGRectMake(30, 120, 100, 40);
    [but1 setTitle:@"Login" forState:UIControlStateNormal];
    [but1 addTarget:self action:@selector(Login) forControlEvents:UIControlEventTouchUpInside];
  //  [but setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateNormal];
    [self.view addSubview:but1];
    but2=[[UIButton alloc]init];
    but2=[UIButton buttonWithType:UIButtonTypeCustom];
    but2.backgroundColor=[UIColor colorWithRed:0.0 green:0.0 blue:0.5 alpha:0.6];
    but2.frame=CGRectMake(320, 120, 100, 40);
    [but2 setTitle:@"Logout" forState:UIControlStateNormal];
    [but2 addTarget:self action:@selector(Logout) forControlEvents:UIControlEventTouchUpInside];
   // [but setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateNormal];
    [self.view addSubview:but2];
    but=[[UIButton alloc]init];
    but=[UIButton buttonWithType:UIButtonTypeCustom];
    but.backgroundColor=[UIColor colorWithRed:0.0 green:0.0 blue:0.5 alpha:0.6];
    but.frame=CGRectMake(150, 60, 150, 40);
    [but setTitle:@"Image To FB" forState:UIControlStateNormal];
    [but addTarget:self action:@selector(ImageToFB) forControlEvents:UIControlEventTouchUpInside];
    //  [but setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateNormal];
    but.tag=0;
    [self.view addSubview:but];
    but3=[[UIButton alloc]init];
    but3=[UIButton buttonWithType:UIButtonTypeCustom];
    but3.backgroundColor=[UIColor colorWithRed:0.0 green:0.0 blue:0.5 alpha:0.6];
    but3.frame=CGRectMake(150, 120, 150, 40);
    [but3 setTitle:@"Message/Link To FB" forState:UIControlStateNormal];
    [but3 addTarget:self action:@selector(LinkMsg) forControlEvents:UIControlEventTouchUpInside];
    //  [but setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateNormal];
    but3.tag=1;
    [self.view addSubview:but3];
    but4=[[UIButton alloc]init];
    but4=[UIButton buttonWithType:UIButtonTypeCustom];
    but4.backgroundColor=[UIColor colorWithRed:0.0 green:0.0 blue:0.5 alpha:0.6];
    but4.frame=CGRectMake(150, 180, 150, 40);
    [but4 setTitle:@"Video To FB" forState:UIControlStateNormal];
    [but4 addTarget:self action:@selector(VideoMsg) forControlEvents:UIControlEventTouchUpInside];
    //  [but setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateNormal];
    but4.tag=2;
    [self.view addSubview:but4];

    // Do any additional setup after loading the view, typically from a nib.
}
-(void)Login
{
    facebook = [[Facebook alloc] initWithAppId:@"455462677804828" andDelegate:self];
    permissions = [[NSArray alloc] initWithObjects:@"publish_stream", nil];
    [self CheckForPreviouslySavedTokens];
   
    if (!ISFBCONNECTED)
    [facebook authorize:permissions];
   
    [permissions release];

}
-(void)Logout
{
    [facebook logout:self];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
      // Release any retained subviews of the main view.
}
-(void)CheckForPreviouslySavedTokens
{
    ISFBCONNECTED=NO;
    //check if previous access token files are there in userdefault file
    NSUserDefaults *Default=[NSUserDefaults standardUserDefaults];
    if ([Default objectForKey:@"FBAccessTokenKey"]&&[Default objectForKey:@"FBExpirationDateKey"]) {
        facebook.accessToken=[Default objectForKey:@"FBAccessTokenKey"];
        facebook.expirationDate=[Default objectForKey:@"FBExpirationDateKey"];
       
        if (![facebook isSessionValid]) {
            [facebook authorize:nil];
            ISFBCONNECTED=NO;
        }
        else {
            ISFBCONNECTED=YES;
        }
    }
}
-(void)saveFBAccessTokenKeys
{
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"];
    [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"];
    [defaults synchronize];
}

-(void)removeSavedFacebookTokens
{
    NSUserDefaults *Default=[NSUserDefaults standardUserDefaults];
    if ((facebook.accessToken =[Default objectForKey:@"FBAcessTokenKey"])&&(facebook.expirationDate =[Default objectForKey:@"FBExpirationDateKey"])) {
    [Default removeObjectForKey:@"FBAccessTokenKey"];
    [Default removeObjectForKey:@"FBExpirationDateKey"];
    [Default release];
    }
}
/*fbsession delegate methods*/

- (void)fbDidLogin
{
    [self saveFBAccessTokenKeys];
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"LOgged IN" message:@"SuccessFully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
   
}

-(void)ImageToFB
{
    NSString *msg=@"hello Iphone,How R U?";
    UIImage*img=[UIImage imageNamed:@"castle-architecture-landscape-wallpapers-480x800.jpeg"];
    NSMutableDictionary *params=[NSMutableDictionary dictionaryWithObjectsAndKeys:img,@"source",msg,@"description", @"its all about testing iphone app with uiimage",@"title",nil];
    [facebook requestWithGraphPath:@"me/photos" andParams:params andHttpMethod:@"POST" andDelegate:self];

   
}
-(void)LinkMsg
{
    NSString *link=@"http://www.apple.com/";
    NSString *msg=@"check Out mY Test Link";
    NSMutableDictionary *params=[NSMutableDictionary dictionaryWithObjectsAndKeys:link,@"link",msg,@"message",nil];
    [facebook requestWithGraphPath:@"feed" andParams:params andHttpMethod:@"POST" andDelegate:self];

}
-(void)VideoMsg
{
    /* if recorded video is stored in path.... use below line and pass into videoData*/
    //NSString* recordedVideoOutputPath = [[NSString alloc] initWithFormat:@"%@/%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0], @"initialVideo.mov"];
    /*for posting sample video from resources*/
    NSString *VideoFile=[[NSBundle mainBundle] pathForResource:@"sample" ofType:@"mov"];
    NSData *videoData = [NSData dataWithContentsOfFile:VideoFile];
   
    //displays the title and subtitle while posting video path.
    //NSLog(@"titl %@  des %@",self.title, self.description);//pass this ,if u use dynmaic text's to title key in params
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: videoData, @"video.mov", @"video/quicktime", @"contentType",@"VideoSAmple", @"title",@"Its all about testing video sharing for FB", @"description",nil];
   
    // posting video path to the facebook wall using http method.
    [facebook requestWithGraphPath:@"me/videos"  andParams:params  andHttpMethod:@"POST"  andDelegate:self];
   
   // [VideoFile release];
    //VideoFile = nil;

}
- (void)fbDidNotLogin:(BOOL)cancelled
{
   
}
- (void)fbDidLogout
{
    [self removeSavedFacebookTokens];
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"LOgged OUT" message:@"SuccessFully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    }
- (void)fbSessionInvalidated
{
   
}
/*fbrequest delegate methods*/

- (void)requestLoading:(FBRequest *)request
{
    NSLog(@"request Loading:%@",request);
   
    v=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 480, 320)];
    v.backgroundColor=[UIColor colorWithRed:.05 green:0.7 blue:2.5 alpha:1.0];
    [self.view addSubview:v];
   
    UIImageView *BackImage=[[[UIImageView alloc] init]autorelease];
    BackImage.image=[UIImage imageNamed:@"Facebook-Wallpaper.jpeg"];
    BackImage.frame=CGRectMake(0, 0, 480, 320);
    [v addSubview:BackImage];
   
    UploadCancel=[[UIButton alloc]init];
    UploadCancel=[UIButton buttonWithType:UIButtonTypeCustom];
    UploadCancel.backgroundColor=[UIColor colorWithRed:0.0 green:0.0 blue:0.5 alpha:0.6];
    UploadCancel.frame=CGRectMake(160, 220, 150, 40);
    [UploadCancel setTitle:@"Cancel Upload" forState:UIControlStateNormal];
    [UploadCancel addTarget:self action:@selector(CancelUpload) forControlEvents:UIControlEventTouchUpInside];
    //  [but setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateNormal];

    prog=[[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];
    prog.frame=CGRectMake(110, 120, 250, 30);
    [v addSubview:prog];
}
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"recieved response:%@",response);
    [v removeFromSuperview];
    v = nil;
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
    [v addSubview:UploadCancel];
    UIAlertView *alertV=[[UIAlertView alloc] initWithTitle:@"Connection Error" message:@"Check Ur Internet Connections" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alertV show]; 
}

-(void)CancelUpload
{
    //  prog.progress=(float)nil;
    [v removeFromSuperview];
    v=nil;
    UIAlertView *alertV=[[UIAlertView alloc] initWithTitle:@"UPload Cancelled" message:@"Due to Bad Internet Connections" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alertV show];
}

- (void)request:(FBRequest *)request didLoad:(id)result
{
        NSLog(@"Successfully uplaoded :%@",result);
}
- (void)request:(FBRequest *)request didLoadRawResponse:(NSData *)data
{
   
}

- (void)request:(FBRequest *)request didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
    NSLog(@"%f",(float)totalBytesWritten/totalBytesExpectedToWrite);
    prog.progress=(float)totalBytesWritten/totalBytesExpectedToWrite;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

@end

CLick & build .

when u use to upload any of the content.it just uplaods the content toi FB as shown in console.