Facebook Friends List Swift - ios

I am trying to run a function to see Facebook friends so users can see which are currently using the app. I have done some researching and found some older code but nothing that works with Swift 3. Here is what I have right now:
var fbRequestFriends: FBSDKGraphRequest = FBSDKGraphRequest.requestForMyFriends()
fbRequestFriends.startWithCompletionHandler{
(connection:FBSDKGraphRequestConnection!,result:AnyObject?, error:NSError!) -> Void in
if error == nil && result != nil {
print("Request Friends result : \(result!)")
} else {
print("Error \(error)")
}
}
It will not run because FBSDKGraphRequest does not have a requestForMyFriends. Does anyone know how to update this in order to work on swift 3?
I have also found this on Facebook Docs but it is all in Obj C but am having issues converting it:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/{friend-list-id}"
parameters:params
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
// Handle the result
}];

Code that you looking for is:
var fbRequestFriends: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/{friend-list-id}", parameters: [AnyHashable : Any]())
fbRequestFriends.start { (connection, result, error) in
if error == nil && result != nil {
print("Request Friends result : \(result!)")
} else {
print("Error \(error)")
}
}
It will execute the request, I do not guarantee that it will work for various reasons, for example - you need permission to ask for a friends list.

Related

can i get user name from Facebook api? , I need user name to use [duplicate]

This question already has answers here:
How to get username from Facebook SDK 4.0 in ios
(4 answers)
Closed 4 years ago.
Hi I just use this api for getting user details but I can't get user name please help me
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"id,first_name,last_name,gender,email,picture.type(large),groups" forKey:#"fields"]]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (error==nil) {
}else {
NSLog(#"facebook erro : %# ",error);
}
}];
You need to ask permissions to access data which is not public.
Check the blog here, it mentions how to request permission for private data.
This is a snippet from the above blog
let loginManager = FBSDKLoginManager()
let permissions = ["public_profile", "email","username"] //not sure username is to be used or user_name.
let handler = loginManager.logInWithReadPermissions(permissions, fromViewController: self, handler: handler)
After the user grants access to his private data. You will be able to retrieve the data.
Facebook iOS sdk get user name and email in swift 3 -
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
let fbDetails = result as! NSDictionary
print(fbDetails)
}else{
print(error?.localizedDescription ?? "Not found")
}
})

I am trying to get my friend name and ids with graph api v2.4, but data returns empty:

hi i am trying to fetch Facebook friend list who using my app when i try this function i getting empty data
my sample code
let request: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/friends", parameters: nil, HTTPMethod: "GET")
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
print("Friends are : \(result)")
} else {
print("Error Getting Friends \(error)");
}
}
and my output is
FBSDKLog: starting with Graph API v2.4, GET requests for /me/friends should contain an explicit "fields" parameter
ID is: 964865453559288
2015-12-21 18:25:55.635[12226:218972] fb_id 964865453559288
Friends are : {
data = (
);
}
USE user_id to fetch friends.It is working fine . Try it
-(void)fetchFriendList:(NSString*)userid
{
NSString *string = [NSString stringWithFormat:#"/%#/taggable_friends",userid];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:string
parameters:nil];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
///// your results
}];
}

iOS: fetch Facebook friends with pagination using 'next'

I am trying to fetch 'taggable_friends' list from Facebook, where there may be more than 1000 taggable friends, so Facebook paginates the results. Here is the method.
-(void)getsFbTaggableFriends:(NSString *)nextCursor dicFBFriends:(NSMutableArray *) dicFriends failure:(void (^) (NSError *error))failureHandler
{
NSString *qry = #"/me/taggable_friends";
NSMutableDictionary *parameters;
if (nextCursor == nil) {
parameters = nil;
}
else {
parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:nextCursor forKey:#"next"];
}
[FBRequestConnection startWithGraphPath:qry
parameters:parameters
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
if (error) {
NSLog(#"%#", [error localizedDescription]);
}else {
/* handle the result */
NSMutableDictionary *mDicResult = [[NSMutableDictionary alloc]initWithDictionary:result];
for (NSDictionary * fbItem in [mDicResult valueForKey:#"data"])
{
[dicFriends addObject:fbItem];
}
// if 'next' value is found, then call recursively
if ([[mDicResult valueForKey:#"paging"] objectForKey:#"next"] != nil) {
NSString *nextCursor = mDicResult[#"paging"][#"next"];
NSLog(#"next:%#", [nextCursor substringFromIndex:27]);
[self getsFbTaggableFriends:nextCursor dicFBFriends:dicFriends failure:^(NSError *error) {
failureHandler(error);
}];
}
}
}];
}
Problem:
I get first 1000 records in the 'result' object and the value of the 'next' key is passed as the "parameters" parameter for the recursive call. However, the second iteration doesn't paginate & keeps returning the same 1000 records.
I also tried using the nextCursor value as the startWithGraphPath parameter for the second call instead. It resulted in a different response object with keys like og_object, share, id instead of data & paging.
Please help to properly obtain the taggable friends page by page, as long as 'next' value is present in the response object. Thank you.
Use the returned next endpoint (Graph path portion, including the cursor) as the new Graph path for the subsequent request, instead putting it as the parameter.
I have come across all the answers. Most of the answers are suggesting either URL based pagination or recursively calling function. We can do this from Facebook SDK itself.
var friendsParams = "taggable_friends"
// Save the after cursor in your data model
if let nextPageCursor = user?.friendsNextPages?.after {
friendsParams += ".limit(10)" + ".after(" + nextPageCursor + ")"
} else {
self.user?.friends.removeAll()
}
let requiredParams = friendsParams + "{id, name, first_name, last_name, picture.width(200).height(200)}"
let params = ["fields": requiredParams]
let _ = FBSDKGraphRequest(graphPath: "me", parameters: params).start { connection, response, error in
if connection?.urlResponse.statusCode == 200 {
print("\(response)")
// Update the UI and next page (after) cursor
} else {
print("Not able to fetch \(error)")
}
}
You can also find the example project here

Facebook friends list api for swift ios

I have tried to get the facebook friends list for an IOS app, but receiving empty response from facebook.
How to get face book friends list in swift?
In Graph API v2.0 or above, calling /me/friends returns the person's friends who installed the same apps. Additionally, 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.
To get the list of friends who are using your app use following code:
let params = ["fields": "id, first_name, last_name, middle_name, name, email, picture"]
let request = FBSDKGraphRequest(graphPath: "me/friends", parameters: params)
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error != nil {
let errorMessage = error.localizedDescription
/* Handle error */
}
else if result.isKindOfClass(NSDictionary){
/* handle response */
}
}
If you want to access a list of non-app-using friends, then use following code:
let params = ["fields": "id, first_name, last_name, middle_name, name, email, picture"]
let request = FBSDKGraphRequest(graphPath: "me/taggable_friends", parameters: params)
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error != nil {
let errorMessage = error.localizedDescription
}
else if result.isKindOfClass(NSDictionary){
/* Handle response */
}
}
For fetching the friend list must allow user permission user_friends at the time of login.
For swift 3.0 add below code for fetching friend list:
let params = ["fields": "id, first_name, last_name, middle_name, name, email, picture"]
FBSDKGraphRequest(graphPath: "me/taggable_friends", parameters: params).start { (connection, result , error) -> Void in
if error != nil {
print(error!)
}
else {
print(result!)
//Do further work with response
}
}
I hope it works!
Remember only those friends are fetched who are using your app and u should have taken users read permission for user_friends while logging.
var fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil);
fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
println("Friends are : \(result)")
} else {
println("Error Getting Friends \(error)");
}
}
Refer to : https://developers.facebook.com/docs/graph-api/reference/v2.3/user/friends#read
Just making an union here that solved my problems:
From Dheeraj Singh, to get friends using your app:
var request = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil);
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
println("Friends are : \(result)")
} else {
println("Error Getting Friends \(error)");
}
}
And to get all facebook friends, from Meghs Dhameliya, ported to swift:
var request = FBSDKGraphRequest(graphPath:"/me/taggable_friends", parameters: nil);
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
println("Friends are : \(result)")
} else {
println("Error Getting Friends \(error)");
}
}
you can get friend list using taggable_friends
Graph API Reference for User Taggable Friend
/* make the API call */
[FBRequestConnection startWithGraphPath:#"/me/taggable_friends"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
/* handle the result */
}];
Swift - 4
This will only return your facebook friends using the same app.
// First you have to check that `user_friends` has associated with your `Access Token`, If you are getting false, please allow allow this field while you login through facebook.
if FBSDKAccessToken.current().hasGranted("user_friends") {
// Prepare your request
let request = FBSDKGraphRequest.init(graphPath: "me/friends", parameters: params, httpMethod: "GET")
// Make a call using request
let _ = request?.start(completionHandler: { (connection, result, error) in
print("Friends Result: \(String(describing: result))")
})
}
With user_friends permission you can have access to the list of your friends that also use your app, so if your app is not used by any of your friend, the list will be empty. See user_friends permission reference

iOS - getting user's Facebook profile picture

I want to get user's profile picture from Facebook in my app. I am aware of the http request that returns the profile picture:
http://graph.facebook.com/USER-ID/picture?type=small
But for that I need the user-id of my user.
Is there a way to fetch that from somewhere without using the Facebook SDK?
If not, can someone show me a simple way to get the user's id (or the profile picture)?
try this... it's working fine in my code .. and without facebook id you cant get ..
and one more thing you can also pass your facebook username there..
//facebookID = your facebook user id or facebook username both of work well
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
NSData *imageData = [NSData dataWithContentsOfURL:pictureURL];
UIImage *fbImage = [UIImage imageWithData:imageData];
Thanks ..
For getting FacebookId of any user, you will have to integrate Facebook Sdk from where you need to open session allow user to login in to Facebook (If user is already logged in to Facebook app, then it will just take permission from user to get access of the permission). Once you does that, you will get user details of logged in user from where you can get his FacebookId.
For more details please check developers.facebook.com.
In order to get the profile picture you need to know the Facebook user ID of the user. This can be obtained logging into Facebook with Social.framework (if you don't want to use Facebook SDK).
You can use ACAccountStore to request access to user's Facebook account like this:
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookTypeAccount = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[accountStore requestAccessToAccountsWithType:facebookTypeAccount
options:#{ACFacebookAppIdKey: YOUR_APP_ID_KEY, ACFacebookPermissionsKey: #[#"email"]}
completion:^(BOOL granted, NSError *error) {
...
Please refer to instructions already answered in this post.
For information regarding how to obtain a Facebook App ID key (YOUR_APP_ID_KEY), look at Step 3 in this article.
Though it's an older question, the same you can do with iOS SDK 4.x like:
Swift:
let pictureRequest = FBSDKGraphRequest(graphPath: "me/picture?type=large&redirect=false", parameters: nil)
pictureRequest.startWithCompletionHandler({
(connection, result, error: NSError!) -> Void in
if error == nil {
println("\(result)")
} else {
println("\(error)")
}
})
Objective-C:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:#"me/picture?type=large&redirect=false"]
parameters:nil
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (!error){
NSLog(#"result: %#",result);}
else {
NSLog(#"result: %#",[error description]);
}}];
The answer is:
https://graph.facebook.com/v2.4/me?fields=picture&access_token=[yourAccessToken]
if your token is abcdef
then url will be:
https://graph.facebook.com/v2.4/me?fields=picture&access_token=acbdef
According to API explorer
you can use this link
https://developers.facebook.com/tools/explorer?method=GET&path=me%3Ffields%3Dpicture&version=v2.4
then if you want to get code for any platform make this:
go to the end of page and press "Get Code" button
then in appeared dialog choose your platform
and you will see the code
The following solution gets both essential user information and full size profile picture in one go...
The code uses latest Swift SDK for Facebook(facebook-sdk-swift-0.2.0), integrated on Xcode 8.3.3
import FacebookCore
import FacebookLogin
#IBAction func loginByFacebook(_ sender: Any) {
let loginManager = LoginManager()
loginManager.logIn([.publicProfile] , viewController: self) { loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login.")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
print("Logged in!")
let authenticationToken = accessToken.authenticationToken
UserDefaults.standard.set(authenticationToken, forKey: "accessToken")
let connection = GraphRequestConnection()
connection.add(GraphRequest(graphPath: "/me" , parameters : ["fields" : "id, name, picture.type(large)"])) { httpResponse, result in
switch result {
case .success(let response):
print("Graph Request Succeeded: \(response)")
/* Graph Request Succeeded: GraphResponse(rawResponse: Optional({
id = 10210043101335033;
name = "Sachindra Pandey";
picture = {
data = {
"is_silhouette" = 0;
url = "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/13731659_10206882473961324_7366884808873372263_n.jpg?oh=f22b7c0d1c1c24654d8917a1b44c24ad&oe=5A32B6AA";
};
};
}))
*/
print("response : \(response.dictionaryValue)")
case .failed(let error):
print("Graph Request Failed: \(error)")
}
}
connection.start()
}
}
}

Resources