Getting Facebook Username in iPhone App - iphone

How can I get the username once anyone is logged in to facebook through my app ?
I am using :-
FBConnect API.
My Controller.m file-
#import "FacebookPOCViewController.h"
#implementation FacebookPOCViewController
#synthesize session = _session;
#synthesize logoutButton = _logoutButton;
#synthesize loginDialog = _loginDialog;
#synthesize facebookName = _facebookName;
- (void)viewDidLoad {
//PayTai Facebook App
static NSString* kApiKey = #"230600000000";
static NSString* kApiSecret = #"----------------------";
_session = [[FBSession sessionForApplication:kApiKey secret:kApiSecret delegate:self] retain];
// Load a previous session from disk if available. Note this will call session:didLogin if a valid session exists.
[_session resume];
[super viewDidLoad];
}
- (IBAction)loginTapped:(id)sender {
//_posting = YES;
// If we're not logged in, log in first...
if (![_session isConnected]) {
self.loginDialog = nil;
_loginDialog = [[FBLoginDialog alloc] init];
[_loginDialog show];
}
// If we have a session and a name, post to the wall!
else if (_facebookName != nil) {
//[self postToWall];
printf("Session");
}
// Otherwise, we don't have a name yet, just wait for that to come through.
}
- (IBAction)logoutButtonTapped:(id)sender {
[_session logout];
}
#pragma mark FBSessionDelegate methods
- (void)session:(FBSession*)session didLogin:(FBUID)uid {
[self getFacebookName];
}
- (void)session:(FBSession*)session willLogout:(FBUID)uid {
_logoutButton.hidden = YES;
_facebookName = nil;
}
pragma mark Get Facebook Name Helper
- (void)getFacebookName {
NSString* fql = [NSString stringWithFormat:#"select uid,name from user where uid == %lld", _session.uid];
//NSLog(#"%#",_session.uid);
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
[[FBRequest requestWithDelegate:self] call:#"facebook.fql.query" params:params];
}
#pragma mark FBRequestDelegate methods
- (void)request:(FBRequest*)request didLoad:(id)result {
if ([request.method isEqualToString:#"facebook.fql.query"]) {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:#"name"];
self.facebookName = name;
_logoutButton.hidden = NO;
[_logoutButton setTitle:[NSString stringWithFormat:#"Logout as %#", name] forState:UIControlStateNormal];
//if (_posting) {
// [self postToWall];
// _posting = NO;
// }
}
}

Take a look at this. You can get almost any info of the user with the GRAPH api.
http://developers.facebook.com/docs/reference/api/user/
Example
/**
* Request the facebook name for the user
* Response will be obtained on delegate
*/
- (void) getFacebookName {
[facebook requestWithGraphPath:#"me?fields=id,name" andDelegate:self];
}
#pragma mark - FBRequestDelegate methods
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(#"Result: %#", result);
NSDictionary *userInfo = (NSDictionary *)result;
userName = [userInfo objectForKey:#"name"];
fb_id = [userInfo objectForKey:#"id"];
}

Related

facebook integration in iphone with Facebook sdk for ios5 and 6

i have use FAcebook sdk 3.0 to integrate facebook.I have use sample code "HelloFacebookSample"
to post status.
I have change in Info.plist file with my AppId.
I have problem that show armv7s,armv7 architecture problem.I even solve out that by "Build Active Architecture Only "to YEs.
I have code that show button for login/logout for facebook
#import "HFViewController.h"
#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>
#interface HFViewController () <FBLoginViewDelegate>
#property (strong, nonatomic) IBOutlet UIButton *buttonPostStatus;
#property (strong, nonatomic) id<FBGraphUser> loggedInUser;
- (IBAction)postStatusUpdateClick:(UIButton *)sender;
- (void)showAlert:(NSString *)message
result:(id)result
error:(NSError *)error;
#end
#implementation HFViewController
#synthesize shareStringFb;
#synthesize buttonPostStatus = _buttonPostStatus;
#synthesize loggedInUser = _loggedInUser;
- (void)viewDidLoad {
[super viewDidLoad];
// Create Login View so that the app will be granted "status_update" permission.
self.buttonPostStatus.enabled = YES;
FBLoginView *loginview = [[FBLoginView alloc] init];
loginview.frame = CGRectOffset(loginview.frame, 5, 5);
loginview.delegate = self;
[self.view addSubview:loginview];
[loginview sizeToFit];
statusText.text=self.shareStringFb;
{
// if the session is closed, then we open it here, and establish a handler for state changes
}
}
-(IBAction)backClick:(id)sender
{
[self.view removeFromSuperview];
}
- (void)viewDidUnload {
self.buttonPostStatus = nil;
self.loggedInUser = nil;
[super viewDidUnload];
}
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView {
// first get the buttons set for login mode
self.buttonPostStatus.enabled = YES;
}
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
// here we use helper properties of FBGraphUser to dot-through to first_name and
// id properties of the json response from the server; alternatively we could use
// NSDictionary methods such as objectForKey to get values from the my json object
self.loggedInUser = user;
}
- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView {
self.buttonPostStatus.enabled = NO;
}
// Post Status Update button handler
- (IBAction)postStatusUpdateClick:(UIButton *)sender {
// Post a status update to the user's feed via the Graph API, and display an alert view
// with the results or an error.
NSString *message = [NSString stringWithFormat:#"Updating %#'s status at %#",
self.loggedInUser.first_name, [NSDate date]];
[FBRequestConnection startForPostStatusUpdate:self.shareStringFb
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:message result:result error:error];
self.buttonPostStatus.enabled = YES;
}];
self.buttonPostStatus.enabled = NO;
}
// Post Photo button handler
it show one button with login/logout in simulator but when i test in device it doesn't show that button.
Please any one can tell me what is problem?Why it not show that?Is there any other way to integrate Fb in ios 5 and 6 both.
Use for
this facebook sdk (3.1) for iOS6
ViewController.h
#import <FacebookSDK/FacebookSDK.h>
{
NSDictionary *dictionary;
NSString *user_email;
NSString *accessTokan;
NSMutableDictionary *fb_dict;
}
- (IBAction)btn_loginwithfacebook:(id)sender;
{
if (!FBSession.activeSession.isOpen)
{
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error)
{
if (error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else if(session.isOpen)
{
[self btn_loginwithfacebook:sender];
}
}];
return;
}
[FBRequestConnection startWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"picture,id,birthday,email,name,gender,username" forKey:#"fields"] HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (!error)
{
if ([result isKindOfClass:[NSDictionary class]])
{
//NSDictionary *dictionary;
if([result objectForKey:#"data"])
dictionary = (NSDictionary *)[(NSArray *)[result objectForKey:#"data"] objectAtIndex:0];
else
dictionary = (NSDictionary *)result;
//NSLog(#"dictionary : %#",dictionary);
user_email = [dictionary objectForKey:#"email"];
[dictionary retain];
//NSLog(#"%#",user_email);//
}
}
}];
accessTokan = [[[FBSession activeSession] accessTokenData] accessToken];
//NSLog(#"%#",accessTokan);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#",accessTokan]]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
//NSLog(#"%#",str);
fb_dict = [str JSONValue];
[str release];}
FacebookAppID ::370546396320150
URL types
Item 0
URL Schemes
Item 0 ::fb370546396320150

Null access token for facebook

Hi been struggling with this for the past 2 days. I never had the issue before but the access token being returned from facebook is always null no matter what I do.
The code used is from facebook connect IOS sdk. I used the exact same code in other apps but had no issues but for some reason this doesn't work now.
There are also no error codes being printed.
Thanks.
I use in sessionChangeState, this code:
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary *result, NSError *error) {
NSLog(#"access Token %#", FBSession.activeSession.accessToken);
}];
And it return me access token, try it!
Try this code.You will get access token through self.facebook.accessToken .
call facebookbtnclicked method at view did load or anywhere to get access token.
facebook = [[Facebook alloc] initWithAppId:#"227757844008650"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"])
{
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
-(void)facebookbtnclicked
{
NSLog(#"facebook btn clicked");
[self loginToFacebook:self];
}
- (BOOL) isFaceBookLoggedIn
{
if (self.facebook.accessToken)
{
return YES;
}
else {
return NO;
}
}
- (void) logoutFromFacebook: (id) logoutDelegate
{
fbServiceRequestingobj = logoutDelegate;
[facebook logout:self];
}
- (void)loginToFacebook:(id) loginDelegate
{
NSLog(#"login facebook method");
fbServiceRequestingobj = loginDelegate;
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
}
-(void) getuserdata
{
NSLog(#"[appDelegate getuserdata]");
if (fbServiceRequestingobj)
{
fbServiceRequestingobj = nil;
}
[facebook requestWithGraphPath:#"me" andDelegate:self];
[facebook requestWithGraphPath:#"me/friends" andDelegate:self];
}
- (void)fbDidLogout
{
NSLog(#"Did Logout");
if (fbServiceRequestingobj)
{
if ([fbServiceRequestingobj respondsToSelector:#selector(fbDidLogout)])
{
[fbServiceRequestingobj performSelector:#selector(fbDidLogout)];
}
}
fbServiceRequestingobj = nil;
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
if (fbServiceRequestingobj)
{
if ([fbServiceRequestingobj respondsToSelector:#selector(request:didFailWithError:)])
{
[fbServiceRequestingobj request:request didFailWithError:error];
}
}
fbServiceRequestingobj = nil;
}
-(void)fbDidNotLogin:(BOOL)cancelled
{
if (fbServiceRequestingobj)
{
if ([fbServiceRequestingobj respondsToSelector:#selector(fbDidNotLogin:)])
{
//[fbServiceRequestingobj fbDidNotLogin:cancelled];
}
}
fbServiceRequestingobj = nil;
}
- (void)fbDidLogin
{
NSLog(#"fbDidLogin");
//[facebook requestWithGraphPath:#"me/friends" andDelegate:self];
NSLog(#"accesstoken########%#",self.facebook.accessToken);
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
count++;
NSError *error = [request error];
if (!error)
{
NSString *response = [request responseString];
NSDictionary *respdic=[response JSONValue];
if(![[respdic valueForKey:#"id"] isEqualToString:#""])
{
UIAlertView *alert1=[[UIAlertView alloc] initWithTitle:#"" message:#"Photo posted successfully." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert1 show];
}
}
}
- (void)request:(FBRequest *)request didLoad:(id)result
{
if ([result isKindOfClass:[NSArray class]])
{
result = [result objectAtIndex:0];
}
if ([result isKindOfClass:[NSDictionary class]])
{
}
}
if ([result isKindOfClass:[NSData class]])
{
UIImage *profilePicture = [[UIImage alloc] initWithData: result];
}
if (fbServiceRequestingobj)
{
if ([fbServiceRequestingobj respondsToSelector:#selector(request:didLoad:)])
{
[fbServiceRequestingobj request:request didLoad:result];
}
}
fbServiceRequestingobj = nil;
};

Integrate twitter to IPhone application

I am hoping to integrate Twitter to my application. My project is created with ARC support. When i added the Twitter framework i also flagged the .m files with -fno-objc-arc.
I could login to twitter (meaning, the authentication process works), and after the authentication that application crashes when i click the tweet button.
1.) This is what gets called first, twitter authentication works fine.
-(void)loginTwitterUser{
if(_engine) return;
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self];
_engine.consumerKey = #"xxxxxx";
_engine.consumerSecret = #"xxxxxx";
if (![_engine isAuthorized]) {
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engine delegate:self];
if (controller) {
[self presentModalViewController:controller animated:YES];
}
}
_engine - i have declared this is the .h file, but did not synthesize it in the .m
This is where we are going to tweet
-(void)tweetThis:(id)sender{
[_engine sendUpdate:#"Tweet something"];
}
3.) other delagate methods
#pragma mark SA_OAuthTwitterEngineDelegate
- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: data forKey: #"authData"];
[defaults synchronize];
}
- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username {
return [[NSUserDefaults standardUserDefaults] objectForKey: #"authData"];
}
#pragma mark TwitterEngineDelegate
- (void) requestSucceeded: (NSString *) requestIdentifier {
NSLog(#"Request %# succeeded", requestIdentifier);
}
- (void) requestFailed: (NSString *) requestIdentifier withError: (NSError *) error {
NSLog(#"Request %# failed with error: %#", requestIdentifier, error);
}
#pragma mark SA_OAuthTwitterController Delegate
In the NSLog username is null. Why is this ?
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenticated with user %#", username);
}
- (void) OAuthTwitterControllerFailed: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Failure");
}
- (void) OAuthTwitterControllerCanceled: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Canceled");
}
The application crashes in the MGTwitterEngine.m at the return statement.
- (NSString *)sendUpdate:(NSString *)status inReplyTo:(unsigned long)updateID
{
if (!status) {
return nil;
}
NSString *path = [NSString stringWithFormat:#"statuses/update.%#", API_FORMAT];
NSString *trimmedText = status;
if ([trimmedText length] > MAX_MESSAGE_LENGTH) {
trimmedText = [trimmedText substringToIndex:MAX_MESSAGE_LENGTH];
}
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:trimmedText forKey:#"status"];
if (updateID > 0) {
[params setObject:[NSString stringWithFormat:#"%u", updateID] forKey:#"in_reply_to_status_id"];
}
NSString *body = [self _queryStringWithBase:nil parameters:params prefixed:NO];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:params body:body
requestType:MGTwitterUpdateSendRequest
responseType:MGTwitterStatus];
}
How can i resolve this ?
Check your SA_OAuthTwitterEngine.m and try to implement the changes below. You should change http to https.
- (SA_OAuthTwitterEngine *) initOAuthWithDelegate: (NSObject *) delegate {
if (self = (id) [super initWithDelegate: delegate])
{
self.requestTokenURL = [NSURL URLWithString: #"https://twitter.com/oauth/request_token"];
self.accessTokenURL = [NSURL URLWithString: #"https://twitter.com/oauth/access_token"];
self.authorizeURL = [NSURL URLWithString: #"https://twitter.com/oauth/authorize"];
}
return self;
}
There's no reason for you to do that, twitter integration has been optimized.
Check this link http://www.raywenderlich.com/5519/beginning-twitter-in-ios-5

Posting Score to FB using FBConnect

Hi all
Just wondering how I modify my code to post a score to Facebook
Currently all working with the following posting to facebook, just no score
#import "GameOverViewController.h"
#import "SoundEffects.h"
#import "FBConnect.h"
#implementation GameOverViewController
#synthesize scoreLabel, highScore;
#synthesize session = _session;
#synthesize postScoreButton = _postScoreButton;
#synthesize logoutButton = _logoutButton;
#synthesize loginDialog = _loginDialog;
#synthesize facebookName = _facebookName;
#synthesize posting = _posting;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *gameOverPath = [[NSBundle mainBundle] pathForResource:#"gameover" ofType:#"png"];
UIImage *gameOver = [[UIImage alloc] initWithContentsOfFile: gameOverPath];
UIImageView *gameOverViewTemp = [[UIImageView alloc] initWithImage:gameOver];
[self.view addSubview:gameOverViewTemp];
gameOverText = [SpriteHelpers setupAnimatedSprite:self.view numFrames:3 withFilePrefix:#"gameovertext" withDuration:0.4 ofType:#"png" withValue:0];
gameOverText.center = CGPointMake(160, 90);
scoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 320, 70)];
scoreLabel.text = [NSString stringWithFormat:#"%d points", highScore];
[self.view addSubview:scoreLabel];
scoreLabel.textColor = [UIColor whiteColor];
scoreLabel.backgroundColor = [UIColor clearColor];
scoreLabel.font = [UIFont boldSystemFontOfSize:42];
scoreLabel.textAlignment = UITextAlignmentCenter;
[gameOverViewTemp release];
[gameOver release];
// Set these values from your application page on http://www.facebook.com/developers
// Keep in mind that this method is not as secure as using the sessionForApplication:getSessionProxy:delegate method!
// These values are from a dummy facebook app I made called MyGrades - feel free to play around!
static NSString* kApiKey = #"2af22b07c9730d3d502a7a401b9e48d7";
static NSString* kApiSecret = #"738116a372130f659a761078de08b3d4";
_session = [[FBSession sessionForApplication:kApiKey secret:kApiSecret delegate:self] retain];
// Load a previous session from disk if available. Note this will call session:didLogin if a valid session exists.
[_session resume];
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view removeFromSuperview];
[self release];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (IBAction)postScoreTapped:(id)sender {
_posting = YES;
// If we're not logged in, log in first...
if (![_session isConnected]) {
self.loginDialog = nil;
_loginDialog = [[FBLoginDialog alloc] init];
[_loginDialog show];
}
// If we have a session and a name, post to the wall!
else if (_facebookName != nil) {
[self postToWall];
}
// Otherwise, we don't have a name yet, just wait for that to come through.
}
- (IBAction)logoutButtonTapped:(id)sender {
[_session logout];
}
#pragma mark FBSessionDelegate methods
- (void)session:(FBSession*)session didLogin:(FBUID)uid {
[self getFacebookName];
}
- (void)session:(FBSession*)session willLogout:(FBUID)uid {
_logoutButton.hidden = YES;
_facebookName = nil;
}
#pragma mark Get Facebook Name Helper
- (void)getFacebookName {
NSString* fql = [NSString stringWithFormat:
#"select uid,name from user where uid == %lld", _session.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
[[FBRequest requestWithDelegate:self] call:#"facebook.fql.query" params:params];
}
#pragma mark FBRequestDelegate methods
- (void)request:(FBRequest*)request didLoad:(id)result {
if ([request.method isEqualToString:#"facebook.fql.query"]) {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:#"name"];
self.facebookName = name;
_logoutButton.hidden = NO;
[_logoutButton setTitle:[NSString stringWithFormat:#"Facebook: Logout as %#", name] forState:UIControlStateNormal];
if (_posting) {
[self postToWall];
_posting = NO;
}
}
}
#pragma mark Post to Wall Helper
- (void)postToWall {
FBStreamDialog* dialog = [[[FBStreamDialog alloc] init] autorelease];
dialog.userMessagePrompt = #"Enter your message:";
dialog.attachment = [NSString stringWithFormat:#"{\"name\":\"%# just played SpaceRide on the iPhone!\",\"href\":\"http://www.spaceride.me/\",\"caption\":\"%# must be really skillful!\",\"description\":\"\",\"media\":[{\"type\":\"image\",\"src\":\"http://www.spaceride.me/fbicon.png\",\"href\":\"http://www.spaceride.me/\"}]}",
_facebookName, _facebookName];
dialog.actionLinks = #"[{\"text\":\"Get SpaceRide!\",\"href\":\"http://www.spaceride.me/\"}]";
[dialog show];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[scoreLabel release];
[super dealloc];
}
#end
Change:
dialog.attachment = [NSString stringWithFormat:#"{\"name\":\"%# just played SpaceRide on the iPhone!\",\"href\":\"http://www.spaceride.me/\",\"caption\":\"%# must be really skillful!\",\"description\":\"\",\"media\":[{\"type\":\"image\",\"src\":\"http://www.spaceride.me/fbicon.png\",\"href\":\"http://www.spaceride.me/\"}]}",
_facebookName, _facebookName];
To something like:
dialog.attachment = [NSString stringWithFormat:#"{\"name\":\"%# just got %d playing SpaceRide on the iPhone!\",\"href\":\"http://www.spaceride.me/\",\"caption\":\"%# must be really skillful!\",\"description\":\"\",\"media\":[{\"type\":\"image\",\"src\":\"http://www.spaceride.me/fbicon.png\",\"href\":\"http://www.spaceride.me/\"}]}",
_facebookName, score, _facebookName];
Change 'score' to the name of your integer score variable.

How to login and request extended permission in a single call?

OK, so I need my app to be able to post something on the users's wall but I'm not very happy with the solution of showing the login pop-up and then the extended permission request popup.
Can it be done with only one popup? Or even with 2 pop-ups but triggered by a single API call?
It might help -
- (void)viewDidLoad {
FacebookAPIAppDelegate *appDelegate =(FacebookAPIAppDelegate *)[[UIApplication sharedApplication]delegate];
if (appDelegate._session == nil){
appDelegate._session = [FBSession sessionForApplication:_APP_KEY
secret:_SECRET_KEY delegate:self];
}
if(self.loginButton == NULL)
self.loginButton = [[[FBLoginButton alloc] init] autorelease];
loginButton.frame = CGRectMake(0, 0, 200, 50);
[self.view addSubview:loginButton];
[super viewDidLoad];
}
- (void)session:(FBSession*)session didLogin:(FBUID)uid {
self.usersession =session;
NSLog(#"User with id %lld logged in.", uid);
[self getFacebookName];
}
- (void)getFacebookName {
NSString* fql = [NSString stringWithFormat:
#"select uid,name from user where uid == %lld", self.usersession.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
[[FBRequest requestWithDelegate:self] call:#"facebook.fql.query" params:params];
self.post=YES;
}
- (void)request:(FBRequest*)request didLoad:(id)result {
if ([request.method isEqualToString:#"facebook.fql.query"]) {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:#"name"];
self.username = name;
if (self.post) {
[self postToWall];
self.post = NO;
}
}
}
- (void)postToWall {
FBStreamDialog *dialog = [[[FBStreamDialog alloc] init] autorelease];
dialog.userMessagePrompt = #"Enter your message:";
//dialog.attachment = [NSString stringWithFormat:#"{\"name\":\"Check this Mix\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone\",\"caption\":\"Caption\",\"description\":\"Description\",\"media\":[{\"type\":\"image\",\"src\":\"http://img40.yfrog.com/img40/5914/iphoneconnectbtn.jpg\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone/\"}],\"properties\":{\"another link\":{\"text\":\"Facebook home page\",\"href\":\"http://www.facebook.com\"}}}"];
dialog.attachment = [NSString stringWithFormat:#"{\"name\":\"Check this Mix\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone\",\"caption\":\"Caption\",\"media\":[{\"type\":\"image\",\"src\":\"http://img40.yfrog.com/img40/5914/iphoneconnectbtn.jpg\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone/\"}],\"properties\":{\"another link\":{\"text\":\"Facebook home page\",\"href\":\"http://www.facebook.com\"}}}"];
[dialog show];
}
as long as the user has logged in and granted permissions once, he should not need to do so again. here's the code I use:
//these to need to be declared in .h
NSString * currentRequest;
BOOl hasAskedForPermissions;
FBSession * mySession
//then in .m
#synthesize currentRequest
#synthesize hasAskedForPermissions
-(void)viewDidLoad {
static NSString* kApiKey = #"XXXXXXXXXXXXXXXXXXXXXXX";
static NSString* kApiSecret = #"XXXXXXXXXXXXXXXXXXXXXXXXXX";
mySession = [[FBSession alloc] initWithKey:kApiKey secret:kApiSecret getSessionProxy:nil];
}
-(void)resumeConnection {
NSLog(#"resuming connection");
static NSString* kApiKey = #"XXXXXXXXXXXXXXXXXXXXXXX";
static NSString* kApiSecret = #"XXXXXXXXXXXXXXXXXXXXXXXXXX";
if ([mySession resume]) {
}
else {
NSLog(#"session did not resume successfully");
mySession = [[FBSession sessionForApplication:kApiKey
secret:kApiSecret delegate:self] retain];
_loginDialog = [[FBLoginDialog alloc] init];
[_loginDialog show];
}
}
-(void)postStatus {
currentRequest = #"post status";
//NSLog(#"current request: %#", currentRequest);
if (!(mySession.isConnected)) {
[self resumeConnection];
}
else if (mySession.isConnected) {
NSLog(#"session is connected");
//Add your posting code here.
} else {
NSLog(#"session is not connected, did not connect");
}
}
-(void)loadPermissionDialog {
FBPermissionDialog* dialog = [[FBPermissionDialog alloc] initWithSession:_session];
dialog.delegate = self;
dialog.permission = #"read_stream, publish_stream, read_friendlists";
[dialog show];
}
- (void)session:(FBSession *)session didLogin:(FBUID)uid {
NSLog(#"Session Logged in sucessfully");
//NSLog(#"current request: %#", currentRequest);
mySession = session;
if (hasAskedForPermissions) {
if ([currentRequest isEqualToString:#"post status"]) {
[self postStatus];
}
}
else {
NSLog(#"asking for permissions");
hasAskedForPermissions = YES;
//you should save this in UserDefaults and recall it in viewDidLoad
[self loadPermissionDialog];
}
}
I don't know how to actually do the post request, but if you run this code the user should only have to log in and assign permissions once.