get all facebook contacts with swift - ios

I'm trying to get all my facebook contacts. With this code managed to catch however I can not bring the phone information and email contacts. This is my code:
let params = ["fields": "first_name, last_name, name, email, picture, phone"]
let request = FBSDKGraphRequest(graphPath:"/me/taggable_friends", parameters: params);
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
self.appDelegate.dismissHUD()
let resultdict = result as! NSDictionary
self.fbContact = resultdict.objectForKey("data") as! NSArray
print(self.fbContact)
self.loadData()
} else {
self.appDelegate.showError("Time Out")
}
it returns this dictionary:
(
{
"first_name" = xxxx;
id = "AaJRSpI-fYgIaPMaJCHEgCHB59aRecZbRSx0BrvDR_bZV-1W873iXn34kU940C_hc-TaoPnuFDfsJbBYtDSAFWiBfGWBXbxOja0c3NIHhyFqoQ";
"last_name" = xxxx;
name = "xxxx xxxx";
picture = {
data = {
"is_silhouette" = 0;
url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfa1/v/t1.0-1/p50x50/10351160_1463351673922060_1213695234585630315_n.jpg?oh=4c3b52137fc70b5743c7d00c2d=56ECD8DC&__gda__=1456979546_a879ab411cdf61e9293f27f70cd43bdd";
};
};
}
)

This is a facebook Graph API limitation. There is some limitations on the data you can get depending on the role you are. You cannot get your friends email or phone using Graph API.

taggable_friends can ONLY be used for tagging, it does not include any other data. You can only get additional data of friends who authorized your App too.
Btw, you can´t even get the phone of the authorized user, there´s no way to get it at all. And for the email, you have to authorize a user with the email permission.
In general, you can´t get any data of users who did not authorize your App, for privacy reasons.

Related

Get User's friends user ID for app leaderboard scores

So, i'm creating a leaderboard where users can see global scores, regional scores and friends scores who have used the app before. all these scores are fetched and written to the fire store database in firebase along with the user's unique id when they log in with facebook.
I need to get a list of the users friends and their user ids from facebook so I can search the fire store database for their scores using the Facebook id. But I don't know how to get the id out of my result below when getting the list of friends:
func getFriendsFromFB() {
let params = ["fields": "id, first_name, last_name, name, email, picture"]
let graphRequest = FBSDKGraphRequest(graphPath: "/me/friends", parameters: params)
let connection = FBSDKGraphRequestConnection()
connection.add(graphRequest, completionHandler: { (connection, result, error) in
if error == nil {
if let userData = result as? [String:Any] {
print(userData)
}
} else {
print("Error Getting Friends \(error)");
}
})
connection.start()
}
Can someone suggest how I get the user id out of my result in the code above?
Also I do ask for the user_friends permission when asking the user to login.
You're casting the result as a Dictionary, this means the results are stored as key values. You can retrieve values by using dictionary["keyHere"]. I'm not sure how the FB graph result is structured, but you will have to do something like this:
// Don't continue if the result is not a dictionary
guard let userData = result as? [String: Any] else {
return
}
// Now, you can get values from the dictionary
// Let's say the userID is a String
if let userID = userData["id"] as? String {
print(userID)
}

Facebook graph API link parameter returning nil

I am trying to store a logged in facebook user's facebook username (eg www.facebook.com/james.dean01) in order to connect people via messenger (similar to How to open Facebook Messenger and direct to someone?). I am configuring a button which will send a user directly to someones messenger chat but to do so I need their username/facebook URL. I am attempting to use the "link" property (Facebook graph API: https://developers.facebook.com/docs/graph-api/reference/user) to obtain a link to the user's profile which could be used for this purpose, only the link property (printed) returns nil. I am not sure what I am doing wrong. The aim is that each time a user logs in the data is read and the database is updated. Below is the code.
Any help would be greatly appreciated!
import FacebookCore
class FacebookService {
static let instance = FacebookService()
let params = ["fields": "email, first_name, last_name, link, picture, name"]
func recordUserData() {
let graphRequest = GraphRequest(graphPath: "me", parameters: params)
graphRequest.start {
(urlResponse, requestResult) in
switch requestResult {
case .failed(let error):
print("error in graph request:", error)
break
case .success(let graphResponse):
if let responseDictionary = graphResponse.dictionaryValue {
print(responseDictionary)
let link = responseDictionary["link"] as? String
let email = responseDictionary["email"] as? String
let fbId = responseDictionary["id"] as? String
let name = responseDictionary["name"] as? String
let picture = responseDictionary["picture"] as? NSDictionary
let data = picture!["data"] as? NSDictionary
let url = data!["url"] as? String
print("Link: \(link)")
print(url)
}
}
}
}
}
You need to ask for the necessary permission, https://developers.facebook.com/docs/facebook-login/permissions#reference-user_link
And the use of this permission requires review by Facebook, before you can use it in your live app.
Not sure you would get this through review though, because what you would be doing is essentially what it says there is a not allowed use case:
Attempt to programmatically determine someone's Facebook username or canonical User ID.
So no guarantee Facebook will approve this; you can only try and submit it for review and see what feedback you get.

Facebook all_mutual_friends not working

I'm building an iOS app that connects to Facebook's all_mutual_friends API
https://developers.facebook.com/docs/graph-api/reference/user-context/all_mutual_friends/
The app has been reviewed and approved to connect to this API.
When I make the graph call per the documentation:
let params = ["fields":"context.fields(all_mutual_friends.fields(picture.width(500).height(200)))"]
FBSDKGraphRequest(graphPath: "/\(facebookID)", parameters: params, HTTPMethod: "GET").startWithCompletionHandler { (connection, result, error) in
print("result: \(result)")
print("error: \(error)")
}
I get the following result:
result: {
context = {
id = dXNlcl9jb250ZAXh0OgGQ8qbGU5YUiZAKn8g4zuCb1LCMGj3PiCXfe7B72X5DoKkbMpHZA395xRT0iV8D84NQIZBCjJ3VRKC9uNUrMZCiwIeZBOSTRndZCQKi4pgiIgLoxI3xAZD;
};
id = 10208913134493418;
}
The above response is when we have a mutual friend who has the app installed.
Does anyone know how to get the list of mutual friends?
If I am Facebook friends with the person, I successfully receive a list of mutual friends making the same graph call. This is the response:
context = {
"all_mutual_friends" = {
data = (
{
"first_name" = Mary;
picture = {
data = {
height = 200;
"is_silhouette" = 0;
url = "https://...";
width = 200;
};
};
}, //... 24 more results
This is great because there is data, but it is limited to 25 mutual friends. Is there a way to increase the limit above 25?
According to the Facebook documentation you referred above :
The All Mutual Friends API must be called from your server to obtain the full list of mutual friends. Calling this API in JavaScript, Android, or iOS client code will omit some of the results.
This explains the limit you are facing. :)

Get game request ID / Access Facebook game request notification content

I am trying to send requests with data to Facebook friends in my app. The requests are successfully sent and I do get notifications. However the message on the notifications is not what I specify (the notification I get is xxxxx sent you a request. I specified Please help me with 5 lives). Also, I can't access any data of the request received.
This is how I'm sending the request:
func sendLifeRequest(index: Int) {
let content = FBSDKGameRequestContent()
content.message = "Please help me with 5 lives"
content.data = "5lives"
let id = facebookFriends[index].id as NSString
var to: [NSString] = [NSString]()
to.append(id)
content.recipients = to
FBSDKGameRequestDialog.show(with: content, delegate: self)
}
This is how I'm trying to get it in the other end:
FBSDKGraphRequest(graphPath: "https://graph.facebook.com/me/apprequests?access_token=" + FBSDKAccessToken.current().tokenString, parameters: nil).start(completionHandler: { (connection, user, requestError) -> Void in
print(requestError) // prints nil
print(user)
})
print(user) prints:
Optional({
id = "https://graph.facebook.com/me/apprequests";
"og_object" = {
id = xxxxxxxxxxxxx;
type = website;
"updated_time" = "2016-10-19T05:32:20+0000";
};
share = {
"comment_count" = 0;
"share_count" = 0;
};
Update: I found out that if I copy the request ID and copy it for graph path it works. Does anyone knows how to get this ID from receivers end
func gameRequestDialog(_ gameRequestDialog: FBSDKGameRequestDialog!, didCompleteWithResults results: [AnyHashable : Any]!) {
print("request sent")
print(results) // copied ID from here
}
and pasted...
FBSDKGraphRequest(graphPath: THE ID HERE, parameters: nil).start(completionHandler: { (connection, user, requestError) -> Void in
print(requestError) // prints nil
print(user)
})
now print user prints:
Optional({
application = {
category = Games;
id = xxxxxxxxxxxx;
link = "https://www.facebook.com/games/?app_id=1841299476156545";
name = "Crazy Traffic Saga";
};
"created_time" = "2016-10-24T21:25:34+0000";
data = 5lives;
from = {
id = xxxxxxxxxxxx;
name = "xxxxxxxxxxxxxx";
};
id = xxxxxxxxxxxx;
message = "Please help me with 5 lives";
})
The problem is I copied when I log in with the user sending and copied to the user receiving. I still can't just access it just by code from the receiver.
Facebook documentation on Game request says:
"In order to read all the requests for a recipient for you can query the graph as shown below using the recipient's USER ACCESS TOKEN. This will return a list of request ids for that user in the app.
GET https://graph.facebook.com/me/apprequests?access_token=[USER ACCESS TOKEN]"
But thats what I was doing at first...
I found it. the request should be "/me/apprequests"
so:
FBSDKGraphRequest(graphPath: "/me/apprequests", parameters: nil).start(completionHandler: { (connection, user, requestError) -> Void in
})

Facebook Graph API - Getting mutual likes

I have an issue when getting mutual likes with Facebook Graph API. The context is the following:
userA is the requester from an iOS application
userA and userB have granted "user_likes" permission both from the iOS app
userA and userB are not Facebook friends
My app Swift code for this part is the following:
self.FBLoginButton.readPermissions = ["public_profile", "email", "user_friends", "user_birthday", "user_about_me", "user_likes"]
...
...
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: userBFBid, parameters: ["fields": "context.fields(mutual_likes).limit(10)"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil) {
print("Error: \(error)")
} else {
print("res: \(result)")
}
})
The result is the following:
res: {
context = {
id = dXNlcl9jb250ZAXh0OgGQg20zLjrZAswOnuX6*******;
"mutual_likes" = {
data = (
);
summary = {
"total_count" = 0;
};
};
};
id = 101532998**********;
}
As you can see, the mutual likes are not returned.
I made the same request with userA and userC which are Facebook friends, and that works correctly, all their mutual likes are returned.
Again: userA, userB and userC have the app installed and granted the user_likes permission.
Any idea to fix it and to get mutual_likes with two users which are not Facebook friends?
I finally found the issue.
First of all: user likes must be visible by public in FB user account privacy configuration to be accessible by the API even if the user_likes permission is granted.
Source: Facebook graph api empty data when getting user likes
Secondly, if the users are not friends on Facebook, the request must also include the parameter appsecret_proof (https://developers.facebook.com/docs/graph-api/securing-requests). So the request must be performed from your server and not from your app for safety reason. Source: https://developers.facebook.com/bugs/101463963524794/
Hope that helps someone one day!

Resources