FBSDKGraphRequest skipped after being logged in through Facebook with Parse - objective-c

I'm currently having user's log in through Facebook using Parse like so:
// Login PFUser using Facebook
[PFFacebookUtils logInInBackgroundWithReadPermissions:permissionsArray block:^(PFUser *user, NSError *error) {
SHOW_LOADING();
// Eventually kick off a loading animation
if (!error)
{
if (user)
{
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"THE RESULT: %#", result);
}
else
{
NSLog(#"ERROR");
}
}];
}
else
{
}
}
HIDE_LOADING();
}];
I get the log statement saying the user's been logged in, but the FBSDKGraphRequest get's completely skipped and there is no log statement from it at all? I can't seem to get it to get it send the FBSDKGraphRequest no matter what I do. (Tried it with obtaining invitable_friends as well but it got skipped too). By skipping I mean if I set breakpoints, it just hops right over the whole internal code of the FBSDKGraphRequest and no NSLog is displayed.

i think you should call the request after you have login in/sign up the user.TRy again outside logInInBackgroundWithReadPermissions loop.
it should work.
-Also use tagguable_friend instead of invitable_friend

Related

Facebook Graph API Fetching User's Profile Photo

I'm using the Facebook Graph API v2.0. The following call
[FBRequestConnection startWithGraphPath:#"/me/picture" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"%#", result);
} else {
NSLog(#"%#", [error userInfo]);
}
}];
results in this error:
{
NSLocalizedDescription = "Response is a non-text MIME type; endpoints that return images and other binary data should be fetched using NSURLRequest and NSURLConnection";
"com.facebook.sdk:ErrorSessionKey" = "<FBSession: 0x10f036250, state: FBSessionStateOpen, loginHandler: 0x100073a40, appID: 863523550341327, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0x10f0339c0>, expirationDate: 4001-01-01 00:00:00 +0000, refreshDate: 2014-07-27 17:20:14 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(\n installed,\n \"public_profile\",\n email,\n \"user_birthday\",\n \"user_location\",\n \"user_friends\"\n)>";
"com.facebook.sdk:HTTPStatusCode" = 0;
}
Does anyone know why this is happening? All I really need is a response containing a url to my profile picture. In 2012 and earlier, similar questions were asked but the API has changed since then. Please don't mark this as a duplicate unless you're actually sure that the question you redirect me to has a working solution. I've tried a couple of other alternatives such as starting the connection myself and using a graph path such as "/me?fields=picture" but they all result in the same error.
It seems my original call requests an image. To get a text based response that gives a url to the profile photo, the following worked for me:
[FBRequestConnection startWithGraphPath:#"me?fields=picture.height(500),picture.width(500)"completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (error) {
}
}];
For the new Facebook Graph API I use:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me?fields=id,name,picture" //As many fields as you need
parameters:nil
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (!error){
NSDictionary *picture = [(NSDictionary*)result objectForKey:#"picture"];
NSDictionary *data = [picture objectForKey:#"data"];
NSString *url = [data objectForKey:#"url"];
NSData *dataImage = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
}
}];
You can more info about user data here
Load profile picture with the help of this URL template
NSString *imgUrl = [NSString stringWithFormat:#"http://graph.facebook.com/%#/picture", user.id];

Sharing my ios app details on facebook along with a facebook share

I am adding share functionalities on my facebook app.Like When a "saying" is selected there is a button for sharing that "saying" on facebook.And while clicking this button I can only see the shared saying on my facebook page,there isnt any information about my ios app.How can I make everyone knows that this saying is shared through my iOS app? Please help me....
I may be a little late. Hope this helps.
You have to use the Accounts framework and the Social framework to share with your app name.
First make sure you have set up your App on Facebook correctly. Then you can use the Facebook App ID to share your posts through your app.
Here is a sample code that shows you how to use the Accounts framework with the Social Framework :
ACAccountType * facebookAccountType = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// At first, we only ask for the basic read permission
NSArray * permissions = #[#"email"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"275485699289493", ACFacebookAppIdKey, permissions, ACFacebookPermissionsKey, ACFacebookAudienceOnlyMe, ACFacebookAudienceKey, nil];
NSArray *accounts = [self.accountStore accountsWithAccountType:facebookAccountType];
//it will always be the last object with single sign on
self.facebookAccount = [accounts lastObject];
[self.accountStore requestAccessToAccountsWithType:facebookAccountType options:dict completion:^(BOOL granted, NSError *error) {
if (granted && error == nil) {
/**
* The user granted us the basic read permission.
* Now we can ask for more permissions
**/
NSArray *readPermissions = #[ #"publish_actions"];
[dict setObject:readPermissions forKey: ACFacebookPermissionsKey];
[self.accountStore requestAccessToAccountsWithType:facebookAccountType options:dict completion:^(BOOL granted, NSError *error) {
if(granted && error == nil) {
NSDictionary *parameters = #{#"message": #"This Should Work Perfectly !! "};
NSURL *feedURL = [NSURL URLWithString:#"https://graph.facebook.com/me/feed"];
SLRequest *feedRequest = [SLRequest
requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:feedURL
parameters:parameters];
feedRequest.account = self.facebookAccount;
[feedRequest performRequestWithHandler:^(NSData *responseData,
NSHTTPURLResponse *urlResponse, NSError *error)
{
// Handle response
}];
} else {
NSLog(#"error is: %#",[error description]);
}
}];
} else {
NSLog(#"error is: %#",[error description]);
}
}];
}

openActiveSessionWithReadPermissions does not log in automatically

I have recently started using Facebook SDK 3.1, and am encountering some problems with logging in using openActiveSessionWithReadPermissions.
Actually, loggin in works perfectly, if there is a cached token available, it logs in without presenting Facebook UI, and if not, it presents the UI.
The problem occurs after I make a call to reauthorizeWithPublishPermissions. If I call reauthorizeWithPublishPermissions, then close and reopen the application, and make a call to openActiveSessionWithReadPermissions, it presents the Facebook UI and requires the user to say "yes I'm OK with read permissions", even though there is a cached token available.
It only presents the Facebook UI erroneously if I make a call to reauthorizeWithPublishPermissions, otherwise everything works fine.
Open for read code:
[FBSession openActiveSessionWithReadPermissions:readpermissions allowLoginUI:YES
completionHandler:^(FBSession *aSession, FBSessionState status, NSError *error) {
[self sessionStateChanged:[FBSession activeSession] state:status error:error];
if (status != FBSessionStateOpenTokenExtended) {
// and here we make sure to update our UX according to the new session state
FBRequest *me = [[FBRequest alloc] initWithSession:aSession
graphPath:#"me"];
[me startWithCompletionHandler:^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *aUser,
NSError *error) {
self.user = aUser;
aCompletionBlock(aSession, status, error);
}];
}
}];
the sessionStateChanged function:
- (void)sessionStateChanged:(FBSession *)aSession state:(FBSessionState)state error:(NSError *)error {
if (aSession.isOpen) {
// Initiate a Facebook instance and properties
if (nil == self.facebook || state == FBSessionStateOpenTokenExtended) {
self.facebook = [[Facebook alloc]
initWithAppId:FBSession.activeSession.appID
andDelegate:nil];
// Store the Facebook session information
self.facebook.accessToken = FBSession.activeSession.accessToken;
self.facebook.expirationDate = FBSession.activeSession.expirationDate;
}
} else {
// Clear out the Facebook instance
if (state == FBSessionStateClosedLoginFailed) {
[FBSession.activeSession closeAndClearTokenInformation];
}
self.facebook = nil;
}
}
the Publish call, with an empty aPublishAction for testing:
- (void)doPublishAction:(void(^)(FBSession *aSession, NSError *error))aPublishAction {
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) {
NSArray *writepermissions = [[NSArray alloc] initWithObjects:
#"publish_stream",
#"publish_actions",
nil];
[[FBSession activeSession]reauthorizeWithPublishPermissions:writepermissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *aSession, NSError *error){
if (error) {
NSLog(#"Error on public permissions: %#", error);
}
else {
aPublishAction(aSession, error);
}
}];
}
else {
// If permissions present, publish the story
aPublishAction(FBSession.activeSession, nil);
}
}
Thanks for everything in advance, I would be grateful for any and all help!!
You need to add
[FBSession.activeSession handleDidBecomeActive];
to your -(void) applicationDidBecomeActive:(UIApplication *)application method in your app's delegate as stated in the migration guide.
What if you use openActiveSessionWithPermissions instead of openActiveSessionWithReadPermissions?

Why can't I access the facebook friends list after reopening a session in ios

I am upgrading to the facebook 3.0 sdk for ios. Things went well, until I tried to open an existing session after relaunching the application. I am trying to access the list of friends for the facebook user.
if ([[FBSession activeSession] isOpen]) {
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//do something here
}];
}else{
[[self session] openWithCompletionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if ([self isValid]) {
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//log this error we always get
NSLog(#"%#",error);
//do something else
}];
}
}];
}
However I get this error:
Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x1d92ff40 {com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 2500;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:HTTPStatusCode=400}
I've found that if I use the FBSession reauthorize method it allows me to complete the request without error, but it also means I must show UI or switch apps every time we relaunch the application which is unacceptable. Any suggestions on what I should be doing differently?
I was not setting the session on the request after logging in. Simple mistake.
[[self session] openWithCompletionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if ([self isValid]) {
//I should have been doing this
request.session = [FBSession activeSession];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//log this error we always get
NSLog(#"%#",error);
//do something else
}];
}
}];

Get and show images from Facebook in iOS app

I'm developing a iOS app for iPad. I've implemented Instagram API so I can get and use the photos from the user. Can I do the same but with Facebook? Is there any way to access to users' pictures?
Thanks
The Graph API is where you want to start to see what data you're looking for. For user photos, check out:
Albums user has created -
https://developers.facebook.com/docs/reference/api/user/
Info about a photo -
https://developers.facebook.com/docs/reference/api/photo/
I recommend trying different queries using the Graph API explorer:
https://developers.facebook.com/tools/explorer
First make sure you ask for user_photos permission
Entering me/albums in the query gives you a list of albums for the logged in user. Click on an album's ID in the results to see the info for that album. Enter /photos to see photos for that album.
Once you know what you want you can take a look at the iOS SDKs that are built on top of the Graph API and other APIs to authenticate and for what you're interested in, to grab photos.
For iOS SDK info on making requests, see:
https://developers.facebook.com/docs/reference/ios/3.1/class/FBRequestConnection#startWithGraphPath%3AcompletionHandler%3A
So if you want to see say the photos for one album, given an album_id, you would use request code like:
[FBRequestConnection startWithGraphPath:#"<album_id>/photos"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog("Results: %#", result);
}
}
];
Make sure you've asked for user_photos permissions first.
- (IBAction)btnFBTap:(id)sender {
[FBSDKProfile enableUpdatesOnAccessTokenChange:YES];
if ([FBSDKAccessToken currentAccessToken]) {
[self FBLogin];
} else {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile", #"user_photos"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
// Process error
} else if (result.isCancelled) {
// Handle cancellations
} else {
[self FBLogin];
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
}
}];
}
}
- (void)FBLogin {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me"
parameters:#{#"fields":#"id"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
[[MDManager sharedInstance].loadingView hide];
if (!error) {
NSLog(#"fetched user:%#", result);
// For more complex open graph stories, use `FBSDKShareAPI`
// with `FBSDKShareOpenGraphContent`
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:#"/%#/photos", result[#"id"]]
parameters:#{#"type":#"uploaded",
#"fields":#"link,height,width"}
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSLog(#"%#",result); // Return uploaded photos
}];
}
}];
}