How to get UserName in Facebook API ios? - iphone

i'm using Facebook native API for sharing in my iPhone App, i need to know as soon as user logged in i need his username, how can i get this?
Any help is appriciated in advance.

You can use Graph API to do this. Just make a request in fbDidLogin delegate method:
- (void)fbDidLogin {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
[facebook requestWithGraphPath: #"me" andDelegate: self];
}
And then you can get all the information about current user in didLoad method:
- (void)request:(FBRequest*)request didLoadRawResponse:(NSData*)data
{
NSString *response = [[NSString alloc] initWithData: data
encoding:NSUTF8StringEncoding];
NSLog(#"%#", response);
[response release];
}
- (void) request:(FBRequest*)request didLoad:(id)result
{
if ([result isKindOfClass:[NSDictionary class]])
{
NSString *name = [result objectForKey: #"name"];
NSString *fbID = [result objectForKey:#"id"];
}
}

Related

Facebook access token error on iphone

I am trying to get name of facebook user in my app but I am getting
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
My code is :-
In viewdidload
facebook = [[Facebook alloc] initWithAppId:#"233350100117670" andDelegate:self];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"] && [defaults objectForKey:#"FBExpirationDateKey"])
{
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
NSArray *permissions = [[NSArray arrayWithObjects:#"read_stream", #"publish_stream", #"offline_access",nil] retain];
[facebook authorize:permissions];
if (![facebook isSessionValid])
{
[facebook authorize:nil];
}
After that:-
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
NSLog(#"%#", [error localizedDescription]);
NSLog(#"Err details: %#", [error description]);
}
- (void)request:(FBRequest*)request didLoadRawResponse:(NSData*)data
{
NSString *response = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"%#", response);
[response release];
}
- (void) request:(FBRequest*)request didLoad:(id)result
{
if ([result isKindOfClass:[NSDictionary class]])
{
NSString *email = [result objectForKey: #"email"];
fbUserName = [result objectForKey: #"name"];
NSString *facebookId = [result objectForKey: #"id"];
NSString* title=[NSString stringWithFormat:#"%# has won a gold medal on Olympedia quiz",fbUserName];
NSMutableDictionary *params =
[NSMutableDictionary dictionaryWithObjectsAndKeys:title, #"name",#"Feed Dialogs of Olympedia.", #"caption",#"Check out Olmpedia Dialogs.", #"description",#"http://www.facebook.com/olympedia", #"link",#"http://bit.ly/PdpRSD", #"picture",nil];
[facebook dialog:#"feed" andParams:params andDelegate:self];
}
}
And on share button click:-
- (IBAction)shareOnFacebook:(id)sender
{
NSLog(#"Posting message");
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
Please help as I am trying to solve this for hours.strong text

- (void)request:(FBRequest *)request didLoad:(id)result not called

Why does this method never called? who can help me to review my code, i am a green hand.
here is my *.h file
#interface LoginViewController : UIViewController <FBSessionDelegate,FBRequestDelegate,FBDialogDelegate> {
Facebook *facebook;
IBOutlet UITextField *_txt;
NSString *facebookUserID;
I want to get the faceboo user ID,So i called the API '[facebook requestWithGraphPath:#"me" andDelegate:self];'
- (void) fbDidLogin
{
NSLog(#"[LOGIN] Used did login");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
// User has logged in to Facebook, now get their userId from Facebook
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
I know below method will get the user ID,but it never called.
- (void)request:(FBRequest *)request didLoad:(id)result
{
NSLog(#"Inside didLoad");
if ([result isKindOfClass:[NSArray class]])
{
result = [result objectAtIndex:0];
}
// When we ask for user infor this will happen.
if ([result isKindOfClass:[NSDictionary class]])
{
//NSDictionary *hash = result;
NSLog(#"Name: %#", [result objectForKey:#"name"]);
self.facebookUserID = [result objectForKey:#"id"];
NSLog(#"ID: %#", [result objectForKey:#"id"]);
}
}
You need to implement the openURL or handleOpenURL (the latter is prior to ios 4.2). It needs to be implemented in your app delegate, not your view controller.
See fbDidLogin not called. openURL will result in fbDidLogin getting called
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
NSLog(#"============HANDLE OPEN URL");
ViewController *v =(ViewController *) vc;
return [[v facebook] handleOpenURL:url];
}

Getting user information from Facebook using graph API

I want to get basic user information from Facebook, but having some problem in the following code
-(void)checkForAccessToken:(NSString *)urlString {
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"access_token=(.*)&" options:0 error:&error];
if (regex != nil) {
**NSTextCheckingResult *firstMatch = [regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])];
if (firstMatch) {
NSRange accessTokenRange = [firstMatch rangeAtIndex:1];
NSString *accessToken = [urlString substringWithRange:accessTokenRange];
accessToken = [accessToken stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[_delegate accessTokenFound:accessToken];
}**
}
}
In the firstMatch I am getting NULL that's why [_delegate accessTokenFound:accessToken]; this methods not get called.
Can anyone please help me out so that I would be able to user information from Facebook
Thanks in advance.
Call the fbdid login method after initialising it with app id and credentials.-
(void)fbDidLogin {
NSLog(#"fbDidLogin");
isFacebookLoaded=YES;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
NSLog(#"i am in and my acees token is %# %# and call me.CALLshowAloadingView",[facebook accessToken],[facebook expirationDate]) ;
[self.facebook requestWithGraphPath:#"me" andDelegate:self];
if ( [delegate respondsToSelector:#selector(showAloadingView)] )
{
NSLog(#" CALLshowAloadingView");
// calling delegate method. For this method to function, the delegate should be implemented in the calling class.
[delegate showAloadingView];
}
// Inform the delegate that Login is successful
if ( [delegate respondsToSelector:#selector(loginStatus:)] ) {
// calling delegate method. For this method to function, the delegate should be implemented in the calling class.
[delegate loginStatus:YES];
return;
}
}

Facebook API dialog page showing error in second time and after that

I want to share my app details.I just done as same given in facebook tutorial.When user loggen in and dialog page appears and i posted my msg.and it worked fine for first time only.when user tapped a button to share again,the dialog appears and showing error page
"Error occurred with 'Your_APP_NAME'.please try again later."
I followed the tutorial in the facebook link below here. https://developers.facebook.com/docs/mobile/ios/build/
Here it is my code.
-(void)buttonPressed:(id)sender{
facebook = [[Facebook alloc] initWithAppId:#"YOUR_APP_ID" andDelegate:self];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"] && [defaults objectForKey:#"FBExpirationDateKey"]) {
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
if (![facebook isSessionValid]) {
[facebook authorize:nil];
}else{
[self postWall];
}
// Pre 4.2 support
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
return [facebook handleOpenURL:url];
}
- (void)fbDidLogin {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
[self postWall];
}
-(void)postWall{
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
kAppId,#"app_id",
#"https://developers.facebook.com/docs/reference/dialogs/",#"link",
#"http://fbrell.com/f8.jpg",#"picture",
#"Facebook Dialogs",#"name",
#"Reference Documentation",#"caption",
#"Using Dialogs to interact with users.",#"description",
#"Facebook Dialogs are so easy!",#"message",
nil];
[[self facebook] dialog:#"feed" andParams:params andDelegate:self];
}
I do all this code in my viewcontroller file(Not in app delegate).I want to open facebook only when i press the button..So i put these codings in my buttonpressed method.
Try with removing
kAppId,#"app_id"
from your NSMutableDictionary params

Facebook IOS SDK trying to make singleton class?

Hy, i am trying to make from Facebook IOS SDK (Octomber 2011) a class of my own in where i can make all the methods and functions that i need and just import this class in any of my application view controllers and call it.
So this way i don't need to do all the initialization and delegation to the controllers in where i use the facebook.
So i want to do like this, [myfacebookclass initwithappID:myappid]
[myfacebookclass postmessage:#"some message"];
The thing is when i am seting authorizeWithFBAppAuth:YES safariAuth:YES flags in facebook.m ( the original class) and i do a postmessage it redirects me on Facebook Application or Safari and check's for permision, i hit ok and then redirects me in my application and doesn't post message.
WHen i am trying to post message i do like this :
This is in my own facebook class
myfacebookclass *facebook2;
+(void)initWithAppID:(NSString*) facebookAppId {
if (facebook2 == nil) {
facebook2 = [myfacebookclass new];
[facebook2 setWithAppId:facebookAppId];
}
}
- (void) postMessage1:(NSString *)messageToPost {
if ([self.facebook isSessionValid]) {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
self.applicationID, #"api_key",
messageToPost, #"message",
nil];
[self.facebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
} else {
NSArray * neededPermissions = [[[NSArray alloc] initWithObjects:#"user_about_me", #"publish_stream", nil] autorelease];
[self.facebook authorize:neededPermissions];
}
}
+ (void)postMessage:(NSString*) message {
[facebook2 postMessage1:message];
}
I also implemented:
(BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [facebook handleOpenURL:url];
}
i've didn't modified facebook.m or other classes in Facebook IOS SDK.
a good practice when making a singleton class is to use shared instance. Correct singleton also has to include some memory management overridden methods. In your case it can be done like this:
#implementation FacebookManager
static FacebookManager *mySharedFacebookManager;
+ (FacebookManager*)sharedFacebookManager {
#synchronized(self) {
if(mySharedFacebookManager == nil) {
mySharedFacebookManager = [[self alloc] init];
}
}
return mySharedFacebookManager;
}
+ (id)allocWithZone:(NSZone *)zone {
#synchronized(self) {
if(mySharedFacebookManager == nil) {
mySharedFacebookManager = [super allocWithZone:zone];
return mySharedFacebookManager;
}
}
return nil;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX;
}
- (oneway void)release {
}
- (id)autorelease {
return self;
}
In your case you may have Facebook type object as ivar, and some methods to wrap over FB API, for example like this:
- (id)init {
self = [super init];
if(self) {
facebook = [[Facebook alloc] initWithAppId:FB_APP_ID andDelegate:self];
// restore previous session
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"]) {
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
...
}
return self;
}
- (void)login {
NSArray *permissions = [NSArray arrayWithObjects: #"user_about_me", #"publish_stream", nil];
[facebook authorize:permissions];
}
- (void)postToFeed:(NSString*)messageToPost {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
messageToPost, #"message",
nil];
[facebook requestWithGraphPath:#"me/feed"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
From other classes which have to deal with Facebook the construction is simple:
[[FacebookManager sharedFacebookManager] login];
...
[[FacebookManager sharedFacebookManager] postToFeed:#"Hello World!"];
I hope this snippets will help you.
To manage your facebook session you have to remember accessToken manually in FBSessionDelegate methods like that:
- (void)fbDidLogin {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
}
- (void)fbDidLogout {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:#"FBAccessTokenKey"];
[defaults removeObjectForKey:#"FBExpirationDateKey"];
[defaults synchronize];
}