posting comments to facebook results in "user not visible" error - iphone

I am writing a facebook app for iphone, however when I send a request to post a comment I get the following error:
failed with error: Error Domain=api.facebook.com Code=210 "User not visible" UserInfo=0x5a986b0 {request_args=(
{
key = text;
value = "Test comment";
},
{
key = format;
value = XML;
},
{
key = "post_id";
value = "100001297086328_132682710102963";
},
{
key = "call_id";
value = 1279912620;
},
{
key = v;
value = "1.0";
},
{
key = "api_key";
value = XXXXXXXXXXXXXXXXXXXXXXX;
},
{
key = method;
value = "facebook.stream.addComment";
},
{
key = "session_key";
value = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
},
{
key = sig;
value = XXXXXXXXXXXXXXXXXXXXXXXXXXX;
}
When I attempt to comment on the same post with the same user and facebook app using the test console at http://developers.facebook.com/docs/reference/rest/stream.addComment it works just fine.
My current permissions are: read_stream, publish_stream, read_friendlists
The code I am using for the request is:
-(void)postComment:(NSString *)comment forPost:(NSString *)postID {
NSLog(#"postComment called");
NSLog(#"comment is: %#", comment);
NSLog(#"post ID is: %#", postID);
currentRequest = #"post comment";
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
comment, #"text",
postID, #"post_id",
nil];
[[FBRequest requestWithDelegate:self] call:#"facebook.stream.addComment" params:params];
}
I can "like" the same post. I have no idea why this isn't working.

Turns out the answer is to update the iOS SDK classes provided by Facebook. The new ones connect via desktop authentification with an access token which lets you use the new graph API to add comments.
The new SDK can be found here: http://github.com/facebook/facebook-ios-sdk/
it will require some changes to current methods, but nothing too complicated.

Check whether 2 users are in friends list of each other...?
It may be possible many time, that you added into cache and polling data from it... which may consist old data and throws this type of error.

Related

Why may I be getting empty data field from facebook? [duplicate]

I am trying to get my friend name and ids with Graph API v2.0, but data returns empty:
{
"data": [
]
}
When I was using v1.0, everything was OK with the following request:
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %i friends", friends.count);
for (NSDictionary<FBGraphUser>* friend in friends) {
NSLog(#"I have a friend named %# with id %#", friend.name, friend.id);
}
}];
But now I cannot get friends!
In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission). This has been confirmed by Facebook as 'by design'.
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
UPDATE: Facebook have published an FAQ on these changes here: https://developers.facebook.com/docs/apps/faq which explain all the options available to developers in order to invite friends etc.
Although Simon Cross's answer is accepted and correct, I thought I would beef it up a bit with an example (Android) of what needs to be done. I'll keep it as general as I can and focus on just the question. Personally I wound up storing things in a database so the loading was smooth, but that requires a CursorAdapter and ContentProvider which is a bit out of scope here.
I came here myself and then thought, now what?!
The Issue
Just like user3594351, I was noticing the friend data was blank. I found this out by using the FriendPickerFragment. What worked three months ago, no longer works. Even Facebook's examples broke. So my issue was 'How Do I create FriendPickerFragment by hand?
What Did Not Work
Option #1 from Simon Cross was not strong enough to invite friends to the app. Simon Cross also recommended the Requests Dialog, but that would only allow five requests at a time. The requests dialog also showed the same friends during any given Facebook logged in session. Not useful.
What Worked (Summary)
Option #2 with some hard work. You must make sure you fulfill Facebook's new rules: 1.) You're a game 2.) You have a Canvas app (Web Presence) 3.) Your app is registered with Facebook. It is all done on the Facebook developer website under Settings.
To emulate the friend picker by hand inside my app I did the following:
Create a tab activity that shows two fragments. Each fragment shows a list. One fragment for available friend (/me/friends) and another for invitable friends (/me/invitable_friends). Use the same fragment code to render both tabs.
Create an AsyncTask that will get the friend data from Facebook. Once that data is loaded, toss it to the adapter which will render the values to the screen.
Details
The AsynchTask
private class DownloadFacebookFriendsTask extends AsyncTask<FacebookFriend.Type, Boolean, Boolean> {
private final String TAG = DownloadFacebookFriendsTask.class.getSimpleName();
GraphObject graphObject;
ArrayList<FacebookFriend> myList = new ArrayList<FacebookFriend>();
#Override
protected Boolean doInBackground(FacebookFriend.Type... pickType) {
//
// Determine Type
//
String facebookRequest;
if (pickType[0] == FacebookFriend.Type.AVAILABLE) {
facebookRequest = "/me/friends";
} else {
facebookRequest = "/me/invitable_friends";
}
//
// Launch Facebook request and WAIT.
//
new Request(
Session.getActiveSession(),
facebookRequest,
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
FacebookRequestError error = response.getError();
if (error != null && response != null) {
Log.e(TAG, error.toString());
} else {
graphObject = response.getGraphObject();
}
}
}
).executeAndWait();
//
// Process Facebook response
//
//
if (graphObject == null) {
return false;
}
int numberOfRecords = 0;
JSONArray dataArray = (JSONArray) graphObject.getProperty("data");
if (dataArray.length() > 0) {
// Ensure the user has at least one friend ...
for (int i = 0; i < dataArray.length(); i++) {
JSONObject jsonObject = dataArray.optJSONObject(i);
FacebookFriend facebookFriend = new FacebookFriend(jsonObject, pickType[0]);
if (facebookFriend.isValid()) {
numberOfRecords++;
myList.add(facebookFriend);
}
}
}
// Make sure there are records to process
if (numberOfRecords > 0){
return true;
} else {
return false;
}
}
#Override
protected void onProgressUpdate(Boolean... booleans) {
// No need to update this, wait until the whole thread finishes.
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
/*
User the array "myList" to create the adapter which will control showing items in the list.
*/
} else {
Log.i(TAG, "Facebook Thread unable to Get/Parse friend data. Type = " + pickType);
}
}
}
The FacebookFriend class I created
public class FacebookFriend {
String facebookId;
String name;
String pictureUrl;
boolean invitable;
boolean available;
boolean isValid;
public enum Type {AVAILABLE, INVITABLE};
public FacebookFriend(JSONObject jsonObject, Type type) {
//
//Parse the Facebook Data from the JSON object.
//
try {
if (type == Type.INVITABLE) {
//parse /me/invitable_friend
this.facebookId = jsonObject.getString("id");
this.name = jsonObject.getString("name");
// Handle the picture data.
JSONObject pictureJsonObject = jsonObject.getJSONObject("picture").getJSONObject("data");
boolean isSilhouette = pictureJsonObject.getBoolean("is_silhouette");
if (!isSilhouette) {
this.pictureUrl = pictureJsonObject.getString("url");
} else {
this.pictureUrl = "";
}
this.invitable = true;
} else {
// Parse /me/friends
this.facebookId = jsonObject.getString("id");
this.name = jsonObject.getString("name");
this.available = true;
this.pictureUrl = "";
}
isValid = true;
} catch (JSONException e) {
Log.w("#", "Warnings - unable to process Facebook JSON: " + e.getLocalizedMessage());
}
}
}
Facebook has revised their policies now. You can’t get the whole friendlist anyway if your app does not have a Canvas implementation and if your app is not a game. Of course there’s also taggable_friends, but that one is for tagging only.
You will be able to pull the list of friends who have authorised the app only.
The apps that are using Graph API 1.0 will be working till April 30th, 2015 and after that it will be deprecated.
See the following to get more details on this:
User Friends
Facebook Application Development FAQ
In Swift 4.2 and Xcode 10.1:
If you want to get the friends list from Facebook, you need to submit your app for review in Facebook. See some of the Login Permissions:
Login Permissions
Here are the two steps:
1) First your app status is must be in Live
2) Get required permissions form Facebook.
1) Enable our app status live:
Go to the apps page and select your app
https://developers.facebook.com/apps/
Select status in the top right in Dashboard.
Submit privacy policy URL
Select category
Now our app is in Live status.
One step is completed.
2) Submit our app for review:
First send required requests.
Example: user_friends, user_videos, user_posts, etc.
Second, go to the Current Request page
Example: user_events
Submit all details
Like this submit for all requests (user_friends , user_events, user_videos, user_posts, etc.).
Finally submit your app for review.
If your review is accepted from Facebook's side, you are now eligible to read contacts, etc.
As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.
this is against Facebook policy, so depending on the country where you live, this may not be legal
you'll have to use your credentials / ask user for credentials and possibly store them (storing passwords even symmetrically encrypted is not a good idea)
when Facebook changes their API, you'll have to update the browser automation code as well (if you can't force updates of your application, you should put browser automation piece out as a webservice)
this is bypassing the OAuth concept
on the other hand, my feeling is that I'm owning my data including the list of my friends and Facebook shouldn't restrict me from accessing those via the API
Sample implementation using WatiN:
class FacebookUser
{
public string Name { get; set; }
public long Id { get; set; }
}
public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
{
var users = new List<FacebookUser>();
Settings.Instance.MakeNewIeInstanceVisible = false;
using (var browser = new IE("https://www.facebook.com"))
{
try
{
browser.TextField(Find.ByName("email")).Value = email;
browser.TextField(Find.ByName("pass")).Value = password;
browser.Form(Find.ById("login_form")).Submit();
browser.WaitForComplete();
}
catch (ElementNotFoundException)
{
// We're already logged in
}
browser.GoTo("https://www.facebook.com/friends");
var watch = new Stopwatch();
watch.Start();
Link previousLastLink = null;
while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
{
var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
&& l.GetAttributeValue("data-hovercard").Contains("user.php")
&& l.Text != null
).LastOrDefault();
if (lastLink == null || previousLastLink == lastLink)
{
break;
}
var ieElement = lastLink.NativeElement as IEElement;
if (ieElement != null)
{
var htmlElement = ieElement.AsHtmlElement;
htmlElement.scrollIntoView();
browser.WaitForComplete();
}
previousLastLink = lastLink;
}
var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
&& l.GetAttributeValue("data-hovercard").Contains("user.php")
&& l.Text != null
).ToList();
var idRegex = new Regex("id=(?<id>([0-9]+))");
foreach (var link in links)
{
string hovercard = link.GetAttributeValue("data-hovercard");
var match = idRegex.Match(hovercard);
long id = 0;
if (match.Success)
{
id = long.Parse(match.Groups["id"].Value);
}
users.Add(new FacebookUser
{
Name = link.Text,
Id = id
});
}
}
return users;
}
Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.
Try /me/taggable_friends?limit=5000 using your JavaScript code
Or
try the Graph API:
https://graph.facebook.com/v2.3/user_id_here/taggable_friends?access_token=
If you are still struggling with this issue on a development mode.
Follow the same process as mentioned below:
create a test app of your main app,
create test users, automatically install app for test users and assign them 'user_friend' permission.
Add your test users as a friend with each other.
I followed the same process after going through alot of research and finally it worked.
In the Facebook SDK Graph API v2.0 or above, you must request the user_friends permission from each user in the time of Facebook login since user_friends is no longer included by default in every login; we have to add that.
Each user must grant the user_friends permission in order to appear in the response to /me/friends.
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
fbLoginManager.logIn(withReadPermissions: ["email","user_friends","public_profile"], from: self) { (result, error) in
if (error == nil) {
let fbloginresult : FBSDKLoginManagerLoginResult = result!
if fbloginresult.grantedPermissions != nil {
if (fbloginresult.grantedPermissions.contains("email")) {
// Do the stuff
}
else {
}
}
else {
}
}
}
So at the time of Facebook login, it prompts with a screen which contain all the permissions:
If the user presses the Continue button, the permissions will be set. When you access the friends list using Graph API, your friends who logged into the application as above will be listed
if ((FBSDKAccessToken.current()) != nil) {
FBSDKGraphRequest(graphPath: "/me/friends", parameters: ["fields" : "id,name"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil) {
print(result!)
}
})
}
The output will contain the users who granted the user_friends permission at the time of login to your application through Facebook.
{
data = (
{
id = xxxxxxxxxx;
name = "xxxxxxxx";
}
);
paging = {
cursors = {
after = xxxxxx;
before = xxxxxxx;
};
};
summary = {
"total_count" = 8;
};
}

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

I am trying to get my friend name and ids with Graph API v2.0, but data returns empty:
{
"data": [
]
}
When I was using v1.0, everything was OK with the following request:
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %i friends", friends.count);
for (NSDictionary<FBGraphUser>* friend in friends) {
NSLog(#"I have a friend named %# with id %#", friend.name, friend.id);
}
}];
But now I cannot get friends!
In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission). This has been confirmed by Facebook as 'by design'.
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
UPDATE: Facebook have published an FAQ on these changes here: https://developers.facebook.com/docs/apps/faq which explain all the options available to developers in order to invite friends etc.
Although Simon Cross's answer is accepted and correct, I thought I would beef it up a bit with an example (Android) of what needs to be done. I'll keep it as general as I can and focus on just the question. Personally I wound up storing things in a database so the loading was smooth, but that requires a CursorAdapter and ContentProvider which is a bit out of scope here.
I came here myself and then thought, now what?!
The Issue
Just like user3594351, I was noticing the friend data was blank. I found this out by using the FriendPickerFragment. What worked three months ago, no longer works. Even Facebook's examples broke. So my issue was 'How Do I create FriendPickerFragment by hand?
What Did Not Work
Option #1 from Simon Cross was not strong enough to invite friends to the app. Simon Cross also recommended the Requests Dialog, but that would only allow five requests at a time. The requests dialog also showed the same friends during any given Facebook logged in session. Not useful.
What Worked (Summary)
Option #2 with some hard work. You must make sure you fulfill Facebook's new rules: 1.) You're a game 2.) You have a Canvas app (Web Presence) 3.) Your app is registered with Facebook. It is all done on the Facebook developer website under Settings.
To emulate the friend picker by hand inside my app I did the following:
Create a tab activity that shows two fragments. Each fragment shows a list. One fragment for available friend (/me/friends) and another for invitable friends (/me/invitable_friends). Use the same fragment code to render both tabs.
Create an AsyncTask that will get the friend data from Facebook. Once that data is loaded, toss it to the adapter which will render the values to the screen.
Details
The AsynchTask
private class DownloadFacebookFriendsTask extends AsyncTask<FacebookFriend.Type, Boolean, Boolean> {
private final String TAG = DownloadFacebookFriendsTask.class.getSimpleName();
GraphObject graphObject;
ArrayList<FacebookFriend> myList = new ArrayList<FacebookFriend>();
#Override
protected Boolean doInBackground(FacebookFriend.Type... pickType) {
//
// Determine Type
//
String facebookRequest;
if (pickType[0] == FacebookFriend.Type.AVAILABLE) {
facebookRequest = "/me/friends";
} else {
facebookRequest = "/me/invitable_friends";
}
//
// Launch Facebook request and WAIT.
//
new Request(
Session.getActiveSession(),
facebookRequest,
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
FacebookRequestError error = response.getError();
if (error != null && response != null) {
Log.e(TAG, error.toString());
} else {
graphObject = response.getGraphObject();
}
}
}
).executeAndWait();
//
// Process Facebook response
//
//
if (graphObject == null) {
return false;
}
int numberOfRecords = 0;
JSONArray dataArray = (JSONArray) graphObject.getProperty("data");
if (dataArray.length() > 0) {
// Ensure the user has at least one friend ...
for (int i = 0; i < dataArray.length(); i++) {
JSONObject jsonObject = dataArray.optJSONObject(i);
FacebookFriend facebookFriend = new FacebookFriend(jsonObject, pickType[0]);
if (facebookFriend.isValid()) {
numberOfRecords++;
myList.add(facebookFriend);
}
}
}
// Make sure there are records to process
if (numberOfRecords > 0){
return true;
} else {
return false;
}
}
#Override
protected void onProgressUpdate(Boolean... booleans) {
// No need to update this, wait until the whole thread finishes.
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
/*
User the array "myList" to create the adapter which will control showing items in the list.
*/
} else {
Log.i(TAG, "Facebook Thread unable to Get/Parse friend data. Type = " + pickType);
}
}
}
The FacebookFriend class I created
public class FacebookFriend {
String facebookId;
String name;
String pictureUrl;
boolean invitable;
boolean available;
boolean isValid;
public enum Type {AVAILABLE, INVITABLE};
public FacebookFriend(JSONObject jsonObject, Type type) {
//
//Parse the Facebook Data from the JSON object.
//
try {
if (type == Type.INVITABLE) {
//parse /me/invitable_friend
this.facebookId = jsonObject.getString("id");
this.name = jsonObject.getString("name");
// Handle the picture data.
JSONObject pictureJsonObject = jsonObject.getJSONObject("picture").getJSONObject("data");
boolean isSilhouette = pictureJsonObject.getBoolean("is_silhouette");
if (!isSilhouette) {
this.pictureUrl = pictureJsonObject.getString("url");
} else {
this.pictureUrl = "";
}
this.invitable = true;
} else {
// Parse /me/friends
this.facebookId = jsonObject.getString("id");
this.name = jsonObject.getString("name");
this.available = true;
this.pictureUrl = "";
}
isValid = true;
} catch (JSONException e) {
Log.w("#", "Warnings - unable to process Facebook JSON: " + e.getLocalizedMessage());
}
}
}
Facebook has revised their policies now. You can’t get the whole friendlist anyway if your app does not have a Canvas implementation and if your app is not a game. Of course there’s also taggable_friends, but that one is for tagging only.
You will be able to pull the list of friends who have authorised the app only.
The apps that are using Graph API 1.0 will be working till April 30th, 2015 and after that it will be deprecated.
See the following to get more details on this:
User Friends
Facebook Application Development FAQ
In Swift 4.2 and Xcode 10.1:
If you want to get the friends list from Facebook, you need to submit your app for review in Facebook. See some of the Login Permissions:
Login Permissions
Here are the two steps:
1) First your app status is must be in Live
2) Get required permissions form Facebook.
1) Enable our app status live:
Go to the apps page and select your app
https://developers.facebook.com/apps/
Select status in the top right in Dashboard.
Submit privacy policy URL
Select category
Now our app is in Live status.
One step is completed.
2) Submit our app for review:
First send required requests.
Example: user_friends, user_videos, user_posts, etc.
Second, go to the Current Request page
Example: user_events
Submit all details
Like this submit for all requests (user_friends , user_events, user_videos, user_posts, etc.).
Finally submit your app for review.
If your review is accepted from Facebook's side, you are now eligible to read contacts, etc.
As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.
this is against Facebook policy, so depending on the country where you live, this may not be legal
you'll have to use your credentials / ask user for credentials and possibly store them (storing passwords even symmetrically encrypted is not a good idea)
when Facebook changes their API, you'll have to update the browser automation code as well (if you can't force updates of your application, you should put browser automation piece out as a webservice)
this is bypassing the OAuth concept
on the other hand, my feeling is that I'm owning my data including the list of my friends and Facebook shouldn't restrict me from accessing those via the API
Sample implementation using WatiN:
class FacebookUser
{
public string Name { get; set; }
public long Id { get; set; }
}
public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
{
var users = new List<FacebookUser>();
Settings.Instance.MakeNewIeInstanceVisible = false;
using (var browser = new IE("https://www.facebook.com"))
{
try
{
browser.TextField(Find.ByName("email")).Value = email;
browser.TextField(Find.ByName("pass")).Value = password;
browser.Form(Find.ById("login_form")).Submit();
browser.WaitForComplete();
}
catch (ElementNotFoundException)
{
// We're already logged in
}
browser.GoTo("https://www.facebook.com/friends");
var watch = new Stopwatch();
watch.Start();
Link previousLastLink = null;
while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
{
var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
&& l.GetAttributeValue("data-hovercard").Contains("user.php")
&& l.Text != null
).LastOrDefault();
if (lastLink == null || previousLastLink == lastLink)
{
break;
}
var ieElement = lastLink.NativeElement as IEElement;
if (ieElement != null)
{
var htmlElement = ieElement.AsHtmlElement;
htmlElement.scrollIntoView();
browser.WaitForComplete();
}
previousLastLink = lastLink;
}
var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
&& l.GetAttributeValue("data-hovercard").Contains("user.php")
&& l.Text != null
).ToList();
var idRegex = new Regex("id=(?<id>([0-9]+))");
foreach (var link in links)
{
string hovercard = link.GetAttributeValue("data-hovercard");
var match = idRegex.Match(hovercard);
long id = 0;
if (match.Success)
{
id = long.Parse(match.Groups["id"].Value);
}
users.Add(new FacebookUser
{
Name = link.Text,
Id = id
});
}
}
return users;
}
Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.
Try /me/taggable_friends?limit=5000 using your JavaScript code
Or
try the Graph API:
https://graph.facebook.com/v2.3/user_id_here/taggable_friends?access_token=
If you are still struggling with this issue on a development mode.
Follow the same process as mentioned below:
create a test app of your main app,
create test users, automatically install app for test users and assign them 'user_friend' permission.
Add your test users as a friend with each other.
I followed the same process after going through alot of research and finally it worked.
In the Facebook SDK Graph API v2.0 or above, you must request the user_friends permission from each user in the time of Facebook login since user_friends is no longer included by default in every login; we have to add that.
Each user must grant the user_friends permission in order to appear in the response to /me/friends.
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
fbLoginManager.logIn(withReadPermissions: ["email","user_friends","public_profile"], from: self) { (result, error) in
if (error == nil) {
let fbloginresult : FBSDKLoginManagerLoginResult = result!
if fbloginresult.grantedPermissions != nil {
if (fbloginresult.grantedPermissions.contains("email")) {
// Do the stuff
}
else {
}
}
else {
}
}
}
So at the time of Facebook login, it prompts with a screen which contain all the permissions:
If the user presses the Continue button, the permissions will be set. When you access the friends list using Graph API, your friends who logged into the application as above will be listed
if ((FBSDKAccessToken.current()) != nil) {
FBSDKGraphRequest(graphPath: "/me/friends", parameters: ["fields" : "id,name"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil) {
print(result!)
}
})
}
The output will contain the users who granted the user_friends permission at the time of login to your application through Facebook.
{
data = (
{
id = xxxxxxxxxx;
name = "xxxxxxxx";
}
);
paging = {
cursors = {
after = xxxxxx;
before = xxxxxxx;
};
};
summary = {
"total_count" = 8;
};
}

How do i get the facebook username of a given PFUser?

PFUser *aUser = [PFUser currentUser]; //may not be the current user NSLog("username %#", [aUser username]); //This is ok if its not a FB user. otherwhise it gives me a token. I know there is a [PFUser isLinkedWithUser:aUser] that returns is the CURRENT LOGGED USER is linked, but aUser may not be the the current in this device.
This works ok for the currentUser:
+ (void)getUsernameWithCompletionBlock:(void(^)(NSString *username))handler {
if([PFFacebookUtils isLinkedWithUser:[PFUser currentUser]]){ //<-
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSDictionary *userData = (NSDictionary *)result;
NSString *name = userData[#"name"];
handler(name);
}}];
} else {
handler([[PFUser currentUser] username]);
}
}
But i want something like this
+(void)getUsernameWithUser:(PFUser *)user andCompletionBlock:(void(^)(NSString *username))handler {
if([PFFacebookUtils isLinkedWithUser:user]){ //<- THIS ALWAYS RETURN FALSE
//return the real facebook username
} else {
handler([user username]);
}
}
In the doc says: isLinkedWithUser:
Whether the user has their account linked to Facebook.
(BOOL)isLinkedWithUser:(PFUser *)user Parameters user User to check for a facebook link. The user must be logged in on this device.
Any ideas?
When you have users who aren't the current user, the authData isn't sent. You have two options:
Each user can store their Facebook username (and any other data you want publicly accessible) in the User table.
Create a cloud code function which uses the master key to retrieve the authData and queries for the Facebook username.
For option two, your cloud code should do something similar to the following:
Parse.Cloud.define("facebookAlias", function(request, response) {
Parse.Cloud.useMasterKey();
new Parse.Query(Parse.User).get(request.params.user_id).then(function(user) {
var authData = user.get("authData");
// Quit early for users who aren't linked with Facebook
if (authData === undefined || authData.facebook === undefined) {
response.success(null);
return;
}
return Parse.Cloud.httpRequest({
method: "GET",
url: "https://graph.facebook.com/me",
params: {
access_token: authData.facebook.access_token,
fields: "username",
}
});
}).then(function(json) {
response.success(JSON.parse(json)["username"]);
// Promises will let you bubble up any error, similar to a catch statement
}, function(error) {
response.error(error);
});
});
Disclaimer: the above code is roughly from a personal project but enough has been tweaked that I don't warrant against syntax errors.

Getting Facebooks' Cover Photo via PHP SDK & Graph API

I'd like to know if there is a simple way of retrieving the Cover photo from a user in my application, via the Facebook php sdk.
I managed to retrieve the cover photo id of the album of the cover photo album, but my solution only works partially. (As you can see, it's not efficient, and If more albums will be added, and moved to other pages, thus this will not work).
$albums = $facebook->api('/me/albums','GET');
for($i = 0;$i<count($albums['data']);$i++){
for($j = 0;$j<count($albums['data'][$i]);$j++){
if($albums['data'][$i]['name'] == "Cover Photos"){
echo $facebook->api('/me/albums/'.$albums['data'][$i]['cover_photo'],'GET');
}
}
}
Facebook seems to have added the Cover field to User Object recently
https://graph.facebook.com/facebookuserid?fields=cover will give you the user cover pic Details
Facebook Doc Link : http://developers.facebook.com/docs/reference/api/user/
I think the easiest is to use the graph api:
http://graph.facebook.com/{user_id or page_id}?fields=cover
and parse the returned JSON.
{
"cover": {
"id": "XXX",
"source": "https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-ash4/311205_989690200741_1231438675_n.jpg",
"offset_y": 66
},
"id": "XXXXXX"
}
Facebook has a really poor and outdated documentation...
At the moment there isn't a proper way to do this via Graph API, but with FQL it is possible.
SELECT pic_cover FROM user WHERE uid='yourUserId'
The field pic_cover isn't documented but available.
The response should look like this:
[
{
"pic_cover": {
"cover_id": someId,
"source": "someUrl",
"offset_y": someOffset
}
}
]
The latest versions of Graph API (2.4 is current at the time of writing) support 'picture' field that returns user's profile picture. It's worth checking.
/<user-id>?fields=id,name,picture
I think it is better to ask type of album then name.
$albums = $facebook->api("/me/albums");
$album_id = "";
foreach($albums["data"] as $item){
//echo $item["id"]." - ".$item["name"]." - ".$item["type"]." - ".$item["cover_photo"]."<br/>";
if($item["type"] == "profile"){
$album_id = $item["id"];
$profile_picture_id = $item["cover_photo"];
break;
}
}
Looks like at this stage, pending updated documentation from facebook, that your method is the only "sure fire" way to retrieve the cover of a users timeline.
If you find this method to be slow or inefficient - maybe you could try running it as a cron job and having a minimal update delay.. eg. run the cron twice a day (maybe even more), maybe handle two or three users at a time and have the cron running every 2 minutes...
Not a solution per-say; more of a suggestion.
I use: http://graph.facebook.com/{user_id or page_id}?fields=cover
Return on browser:
{
"cover": {
"id": "XXX",
"source": "https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-ash4/311205_989690200741_1231438675_n.jpg",
"offset_y": 66
},
"id": "XXXXXX"
}
How can I get field 'source' to a php varible?
Sr, I can't reply so i post here. :(
it tries to automatically recover from the image through php
$json = file_get_contents("https://graph.facebook.com/PROFILE_ID?fields=cover");
$obj = json_decode($json);
echo $obj->cover ->source;
I use username instead of id and it works:
http://graph.facebook.com/{username}?fields=cover
Parse the JSON accordingly.
I have used https://graph.facebook.com/facebookuserid?fields=cover link but it did not work. When I search Facebook SDK documentation, I see the answer that works.
I hope this will be helpful for you.
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"/%#?fields=cover", [user objectForKey:#"id"]]
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
NSLog(#"%#",[[result objectForKey:#"cover"]objectForKey:#"source"]);
/* handle the result */
}];
Result is a type of a Dictionary. You can see the link of user's cover photo under "cover" tag and its "source" tag also.
This is how I extracted my cover pic using Jackson and the Graph API.
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode actualObj = mapper.readTree(String.valueOf(object));
JsonNode cover = actualObj.get("cover");
Map<String,String> myMap = mapper.readValue(cover.toString(), HashMap.class);
Log.e("Cover link", myMap.get("source"));
coverpic = myMap.get("source");
} catch (IOException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "cover");
request.setParameters(parameters);
request.executeAsync();
function getCover() {
FB.api('/me?fields=cover', function(response) {
document.getElementById('cover').innerHTML =
"<img src='" + response.cover['source'] + "' alt='' />"
});
}

How to get the Facebook user id using the access token

I have a Facebook desktop application and am using the Graph API.
I am able to get the access token, but after that is done - I don't know how to get the user's ID.
My flow is like this:
I send the user to https://graph.facebook.com/oauth/authorize with all required extended permissions.
In my redirect page I get the code from Facebook.
Then I perform a HTTP request to graph.facebook.com/oauth/access_token with my API key and I get the access token in the response.
From that point on I can't get the user ID.
How can this problem be solved?
If you want to use Graph API to get current user ID then just send a request to:
https://graph.facebook.com/me?access_token=...
The easiest way is
https://graph.facebook.com/me?fields=id&access_token="xxxxx"
then you will get json response which contains only userid.
The facebook acess token looks similar too
"1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc"
if you extract the middle part by using | to split you get
2.h1MTNeLqcLqw__.86400.129394400-605430316
then split again by -
the last part 605430316 is the user id.
Here is the C# code to extract the user id from the access token:
public long ParseUserIdFromAccessToken(string accessToken)
{
Contract.Requires(!string.isNullOrEmpty(accessToken);
/*
* access_token:
* 1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc
* |_______|
* |
* user id
*/
long userId = 0;
var accessTokenParts = accessToken.Split('|');
if (accessTokenParts.Length == 3)
{
var idPart = accessTokenParts[1];
if (!string.IsNullOrEmpty(idPart))
{
var index = idPart.LastIndexOf('-');
if (index >= 0)
{
string id = idPart.Substring(index + 1);
if (!string.IsNullOrEmpty(id))
{
return id;
}
}
}
}
return null;
}
WARNING:
The structure of the access token is undocumented and may not always fit the pattern above. Use it at your own risk.
Update
Due to changes in Facebook.
the preferred method to get userid from the encrypted access token is as follows:
try
{
var fb = new FacebookClient(accessToken);
var result = (IDictionary<string, object>)fb.Get("/me?fields=id");
return (string)result["id"];
}
catch (FacebookOAuthException)
{
return null;
}
You can use below code on onSuccess(LoginResult loginResult)
loginResult.getAccessToken().getUserId();
You just have to hit another Graph API:
https://graph.facebook.com/me?access_token={access-token}
It will give your e-mail Id and user Id (for Facebook) also.
With the newest API, here's the code I used for it
/*params*/
NSDictionary *params = #{
#"access_token": [[FBSDKAccessToken currentAccessToken] tokenString],
#"fields": #"id"
};
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me"
parameters:params
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSDictionary *res = result;
//res is a dict that has the key
NSLog([res objectForKey:#"id"]);
in FacebookSDK v2.1 (I can't check older version). We have
NSString *currentUserFBID = [FBSession activeSession].accessTokenData.userID;
However according to the comment in FacebookSDK
#discussion This may not be populated for login behaviours such as the iOS system account.
So may be you should check if it is available, and then whether use it, or call the request to get the user id
Check out this answer, which describes, how to get ID response.
First, you need to create method get data:
const https = require('https');
getFbData = (accessToken, apiPath, callback) => {
const options = {
host: 'graph.facebook.com',
port: 443,
path: `${apiPath}access_token=${accessToken}`, // apiPath example: '/me/friends'
method: 'GET'
};
let buffer = ''; // this buffer will be populated with the chunks of the data received from facebook
const request = https.get(options, (result) => {
result.setEncoding('utf8');
result.on('data', (chunk) => {
buffer += chunk;
});
result.on('end', () => {
callback(buffer);
});
});
request.on('error', (e) => {
console.log(`error from facebook.getFbData: ${e.message}`)
});
request.end();
}
Then simply use your method whenever you want, like this:
getFbData(access_token, '/me?fields=id&', (result) => {
console.log(result);
});