Authentication Error while extracting user information with Facebook Graph API - ios

I am trying to extract user's basic information through FBConnect latest SDK. My code is simple:
- (void)viewDidLoad {
[super viewDidLoad];
facebook = [[Facebook alloc] initWithAppId:fbAppId];
NSArray* permissions = [[NSArray arrayWithObjects:#"user_about_me",#"read_stream",nil]retain];
[facebook authorize:permissions delegate:self];
[facebook requestWithGraphPath:#"me" andDelegate:self];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
fbAppId, #"app_id",
[NSString stringWithFormat: #"Some Text"], #"description",
#"My Test App", #"name",
#"Test Facebook Graph API",#"message",
nil];
[facebook dialog:#"feed" andParams:params andDelegate:self];
}
- (BOOL) application: (UIApplication*) application handleOpenURL:(NSURL *)url {
return [facebook handleOpenURL:url];
}
- (void) fbDidLogin {
NSLog(#"FB didLogin");
}
- (void) fbDidNotLogin:(BOOL)cancelled {
NSLog(#"FB didNotLogin");
}
- (void) request:(FBRequest *)request didLoad:(id)result {
NSLog(#"request-didLoad-result");
}
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(#"received response");
}
Up till this point everything goes well apparently. Publish a feed through dialog on user's wall works fine. The problem occurs when I try to get user's information like name with:
[facebook requestWithGraphPath:#"me" andDelegate:self];
But neither fbDidLogin nor requestDidLoad is called. For requestDidLoad, I checked didLoadRawResponse as it is called before request didLoad:
- (void)request:(FBRequest *)request didLoadRawResponse:(NSData*)data {
NSString *response = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response is = %#",response);
[response release];
}
What I get in response is the following authentication error:
{"error":{"type":"OAuthException","message":"An active access token must be used to query information about the current user."}}
What is the reason and the solution?

I have added my whole code in the following wiki
How to retrieve Facebook response using Facebook iOS SDK
Hope this will help you, this is a working code if you have any question please let me know.

Related

Parse Facebook Dialog Delegate methods not being called

I'm using the Parse SDK to implement a Facebook apprequests dialog in my app. For all intents and purposes it just wraps the Facebook SDK, prefixing Facebook methods with PF_.
I use this code to prepare and raise the dialog:
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSString stringWithFormat:#"I just challenged you to a game!"], #"message",
[friendIds componentsJoinedByString:#"," ], #"to",
nil];
PF_FBSession *session = [PFFacebookUtils session];
PF_Facebook *facebook = [[PF_Facebook alloc] initWithAppId:session.appID andDelegate:nil];
facebook.accessToken = session.accessToken;
facebook.expirationDate = session.expirationDate;
[facebook dialog:#"apprequests" andParams:params andDelegate:self];
This works well, I'm getting the dialog, I'm able to invite friends to play with the app.
The problem is that the delegate methods are not being called, even though I've set the view controller as a PF_FBDialogDelegate:
#interface ChallengeFriendsViewController : UIViewController <UITableViewDelegate, PF_FBDialogDelegate> {
NSArray *facebookFriends;
NSMutableArray *selectedFriends;
}
These are some of the delegate methods I'm talking about:
- (void)dialog:(PF_FBDialog *)dialog didFailWithError:(NSError *)error {
NSLog(#"Error in Dialog: %#", error);
}
- (void)dialogDidNotCompleteWithUrl:(NSURL *)url {
NSLog(#"Failure on Facebook server side");
}
- (void)dialogCompleteWithUrl:(NSURL *)url {
NSLog(#"Did complete with URL");
[self.navigationController popViewControllerAnimated:YES];
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
- (void)dialogDidNotComplete:(PF_FBDialog *)dialog {
NSLog(#"Cancelled");
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
Without these methods being called I'm really not able to handle the sharing in an intuitive way. I'm stumped as to why they wouldn't be called and feel I've tried everything. Any pointers to where I'm going wrong?
In your code you have
PF_Facebook *facebook = [[PF_Facebook alloc] initWithAppId:session.appID andDelegate:nil];
Since you set a nil delegate, I would expect the delegate methods are never called, as you describe.
Could you change this to
PF_Facebook *facebook = [[PF_Facebook alloc] initWithAppId:session.appID andDelegate:self];
That is assuming that you put the delegate methods in the same class.
I finally got around the problem by using the facebook instance provided by PFFacebookUtils. This is deprecated but appears to be the only way to make it call the correct delegate methods at the moment.
Replaced:
PF_Facebook *facebook = [[PF_Facebook alloc] initWithAppId:session.appID andDelegate:nil];
With:
PF_Facebook *facebook = [PFFacebookUtils facebook];
Thanks to JP and Aromal for your input.

iOS facebook integration - sending and receiving requests

I use a facebook api to connect to facebook and send request via native dialogs provided by the api.
I followed the sample posted in the docs on developers.facebook.com
But I have following problem sending requests :
1. The requests are not shown in notifications - only in application center - In this case i think that it is a problem of that the app is in sandbox and not posted to APPSTORE
I succesfully send request to facebook server with right fbUser id. But when I want to receive the notification in app here comes the problem :
Following the docs as an authorized user I should se
this in open url method:
fb[APP_ID]://authorize#expires_in=[ACCESS_TOKEN_EXPIRATION]
&access_token=[USER_ACCESS_TOKEN]
&target_url=https://apps.facebook.com/[APP_NAME_SPACE]/?request_ids=
[COMMA_SEPARATED_REQUESTIDs]&ref=notif&app_request_type=user_to_user
But i can see only plain login without targer url .... I can see session expiration date, fb app id, access token and so on. But no target url?
So basically what the target_url is?
How it should be set?
What i have to include when sending request?
In addition :
application handle open url method is called properly.
checkRequests method is also called properly after app becomes active.
Please do not link me to the docs. I have read it moreless 50 times and didn't find any reasonable solution...
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
// attempt to extract a token from the url
self.openedURL = url;
NSLog(#"%#",url);
return [FBSession.activeSession handleOpenURL:url];
}
- (void)sendRequest {
FBSBJSON *jsonWriter = [FBSBJSON new];
NSDictionary *gift = [NSDictionary dictionaryWithObjectsAndKeys:
#"5", #"points",
#"1", #"badge",
nil];
NSString *giftStr = [jsonWriter stringWithObject:gift];
NSMutableDictionary* params =
[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Hi from test app", #"message",
giftStr, #"data",
nil];
[self.facebook dialog:#"apprequests"
andParams:params
andDelegate:self];
}
// Handle the request call back
- (void)dialogCompleteWithUrl:(NSURL *)url {
NSDictionary *params = [self parseURLParams:[url query]];
NSString *requestID = [params valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
}
-(FBSession*)returnSession{
return self.session;
}
/*
* Helper function to get the request data
*/
- (void) notificationGet:(NSString *)requestid {
[FBRequestConnection startWithGraphPath:requestid
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (!error) {
NSString *title;
NSString *message;
if ([result objectForKey:#"data"]) {
title = [NSString
stringWithFormat:#"%# sent you a gift",
[[result objectForKey:#"from"]
objectForKey:#"name"]];
FBSBJSON *jsonParser = [FBSBJSON new];
NSDictionary *requestData =
[jsonParser
objectWithString:[result objectForKey:#"data"]];
message =
[NSString stringWithFormat:#"Badge: %#, Karma: %#",
[requestData objectForKey:#"badge"],
[requestData objectForKey:#"points"]];
} else {
title = [NSString
stringWithFormat:#"%# sent you a request",
[[result objectForKey:#"from"] objectForKey:#"name"]];
message = [NSString stringWithString:
[result objectForKey:#"message"]];
}
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:title
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil,
nil];
[alert show];
// Delete the request notification
[self notificationClear:[result objectForKey:#"id"]];
}
}];
}
/*
* Helper function to check incoming URL
*/
- (void) checkIncomingNotification {
if (self.openedURL) {
NSString *query = [self.openedURL fragment];
if (!query) {
query = [self.openedURL query];
}
NSDictionary *params = [self parseURLParams:query];
for (NSString * str in [params allKeys]) {
NSLog(#"key %#", str);
}
// Check target URL exists
NSString *targetURLString = [params valueForKey:#"target_url"];
if (targetURLString) {
NSURL *targetURL = [NSURL URLWithString:targetURLString];
NSDictionary *targetParams = [self parseURLParams:[targetURL query]];
NSString *ref = [targetParams valueForKey:#"ref"];
// Check for the ref parameter to check if this is one of
// our incoming news feed link, otherwise it can be an
// an attribution link
if ([ref isEqualToString:#"notif"]) {
// Get the request id
NSString *requestIDParam = [targetParams
objectForKey:#"request_ids"];
NSArray *requestIDs = [requestIDParam
componentsSeparatedByString:#","];
// Get the request data from a Graph API call to the
// request id endpoint
[self notificationGet:[requestIDs objectAtIndex:0]];
}
}
// Clean out to avoid duplicate calls
self.openedURL = nil;
}
}
Is there any way that these problems are caused by the way that the app is not published on Appstore (Appstore id is not set neither for iPhone nor iPad)?
Here are code snippets showing using of the fb api:
Thank you very much for the time.
Enable deep linking in Facebook app settings
Facebook sdk 3.5 requests not working
I think this link will help you,configure App on Facebook as well

Not receiving response from facebook

I have a problem when I send a post to my wall from my iPhone app.
I have all the delegate methods implemented and the method:
-(void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
// Keep this just for testing purposes.
NSLog(#"received response");
}
My app works, the post appears on my wall, but my app doesn't get any response and stucks at my activity indicator. Nothing appears in the console from NSLog.
Does any one know, where's the problem? I'm dying here :-/
EDIT:
- (IBAction)fbButtonPressed:(id)sender {
// Create the parameters dictionary that will keep the data that will be posted.
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"330334280387192", #"app_id",
nil];
// Publish.
[self.facebook dialog:#"feed" andParams:params andDelegate:self];
}
I'm using the feed dialog for user input

Facebook scores api with iOS5.1 - Can read scores... but cant post them

I'm new to iOS development, I have successfully integrated facebook login and such... however my problem is with the Score api. i can read the score but i cant seem to post it, i have the publish_actions permission and also am getting back a valid access_token.Not sure what the problem it, here is my code -
NSString *accessTokenToUse = [NSString stringWithFormat:#"%#",[self.facebook accessToken] ];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
//#"233", #"score",
accessTokenToUse, #"access_token",
nil];
NSMutableDictionary *paramsB = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"233", #"score",
accessTokenToUse, #"access_token",
nil];
NSLog(#"APP ACCESS TOKEN: %#",accessTokenToUse);
[self.facebook requestWithGraphPath:#"me/scores" andParams:paramsB andHttpMethod:#"POST" andDelegate:self];
[self.facebook requestWithGraphPath:#"APP_ID/scores" andParams:params andHttpMethod:#"GET" andDelegate:self];
***EDIT - Still doesn't work
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"233", #"score",
#"[APP_ACCESS_TOKEN (omitted for stackoverflow)]", #"access_token", nil];
[self.facebook requestWithGraphPath:#"/[userID]/scores" andParams:params andHttpMethod:#"POST" andDelegate:self];
EDIT - SOLVED
So bascially i WAS passing in the correct token, however the facebook sdk was overwriting it in Facebook.m to the user's access token. So the fix was simple - whenever i need to pass in the App's token i just add an other parameter < key=#"useAppToken" Value=#"yes" > and in Facebook.m just add an if statement within isSessionValid -
- (FBRequest*)openUrl:(NSString *)url
params:(NSMutableDictionary *)params
httpMethod:(NSString *)httpMethod
delegate:(id<FBRequestDelegate>)delegate {
NSLog(#"PARAMS BFORE: %# ", params);
[params setValue:#"json" forKey:#"format"];
[params setValue:kSDK forKey:#"sdk"];
[params setValue:kSDKVersion forKey:#"sdk_version"];
if ([self isSessionValid]) {
if ([params objectForKey:#"useAppToken"] == nil || [params objectForKey:#"useAppToken"] == #"no") {
[params setValue:self.accessToken forKey:#"access_token"];
}
}
NSLog(#"PARAMS AFTER: %# ", params);
[self extendAccessTokenIfNeeded];
FBRequest* _request = [FBRequest getRequestWithParams:params
httpMethod:httpMethod
delegate:delegate
requestURL:url];
[_requests addObject:_request];
[_request addObserver:self forKeyPath:requestFinishedKeyPath options:0 context:finishedContext];
[_request connect];
return _request;
}
Be sure to comment out the NSLogs in this... :)
Scores can only be published using application access_token and not one for user (which you probably using, it's ok for reading the scores but don't allow you to publish 'em).
Citing the Scores documentaion:
Create or update a score for a user
You can post a score or a user by issuing an HTTP POST request to /USER_ID/scores with the app access_token as long as you have the publish_actions permission.
Looks like it's a bug:
http://developers.facebook.com/bugs/461900043821056
But if you change your app settings to web app instead of native it would work.

Error while doing FQLRequest

I am doing a FQL request when in my view controller through a specific method.
Here is my request.
NSString* fql = [[NSString alloc] init];
fql = [NSString stringWithFormat:#"SELECT uid, name FROM user WHERE uid IN(SELECT uid FROM event_member WHERE eid= %#) AND sex='female'", event_id];
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObject:fql forKey:#"query"];
[[Facebook shared] requestWithMethodName:#"fql.query" andParams:params andHttpMethod:#"POST" andDelegate: self];
[fql release];
However, when I just launch my request a second time, I got that error when using NSZombieEnabled :
-[CFString release]: message sent to deallocated instance 0x4cb9ec0
The thread points at [_params release] in FBRequest.m
When trying just changing the request with
fql = #"SELECT uid, name, sex FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND sex = 'male'";
I have no longer the error.
Here are the fbrequest delegate methods
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(#"FBRequestDelegate Received response");
}
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(#"FBRequestDidLoad Received response");
self.allListProfils = result;
NSLog(#"all listprofil :%#", allListProfils);
[self resetSearch];
[DSBezelActivityView removeViewAnimated:YES];
moreButton.hidden = NO;
[table reloadData];
};
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(#"FBRequestDidFailWithError Received response, Error is : %#",[error description]);
};
Does it ring a bell for some of you ?
Thanks :)

Resources