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()
}
}
}
Related
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")
}
})
{com.facebook.sdk:FBSDKGraphRequestErrorGraphErrorCode=2500, com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey={
body = {
error = {
code = 2500;
"fbtrace_id" = DiBO16GER0C;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey=400, com.facebook.sdk:FBSDKErrorDeveloperMessageKey=An active access token must be used to query information about the current user., com.facebook.sdk:FBSDKGraphRequestErrorCategoryKey=0}
I am facing the above error. I know this was already discussed but they fixed using FBSession . In the Latest SDK i did not see the FBSession. Please help me i am stuck on this for whole day.
Issue coming under:
I have 3 pages (Login page, username page, find friends page). In login page i just authenticate with facebook and get the user information from the graphAPI it works fine. Then come to the page username here normal registration process from user. Then i come to the find friends page here i facing the issue that is, If i come with the flow(login -> username -> find friends page) i can list the facebook friends using graphAPI BUT i could not get the friends list when i kill the app and open this page directly it shows above error. I dont know how to get back from this. Please help anybody felt this before.
My code are below,
Find Friends Page:
if ([FBSDKAccessToken currentAccessToken])
{
[[[FBSDKGraphRequest alloc] initWithGraphPath:url parameters:#{ #"fields": #"id,picture"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
NSLog(#"result === %#",result);
if (!error)
{}
else
{}
}];
}
else
{
NSLog(#"There is no current access token");
}
Note:
The current access token is null when i kill the app and come back to the username page again.
Got it!
This will be surely helpful to someone, Actually i did mistake in this place, [[[FBSDKGraphRequest alloc] initWithGraphPath:url parameters:#{ #"fields": #"id,picture"}] This method not have the access token ever. But wonder is the access token is not enable in the whole app. it will be null when i move to the next page after kill the app. So i just save the token string in NSUserDefaults like
NSString *access_token=[FBSDKAccessToken currentAccessToken].tokenString;
[NSUSER setObject:access_token forKey:#"fb_token"];
[NSUSER synchronize];
And then wherever i call the graphAPI i use this method with tokenstring like,
[[[FBSDKGraphRequest alloc] initWithGraphPath:url parameters:#{ #"fields": #"id,picture"} tokenString:[NSUSER objectForKey:#"fb_token"] version:nil HTTPMethod:#"GET"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
}];
Simple but it takes too long to find. Glad!
This will help you in swift 2.0
func application(application: UIApplication,
openURL url: NSURL,
sourceApplication: String?,
annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(
application,
openURL: url,
sourceApplication: sourceApplication,
annotation: annotation)
}
Working fine for me Swift 3
Put this code where friend list or fb user data received:have look
let token = FBSDKAccessToken.current().tokenString
UserDefaults.standard.setValue(token, forKey: "fb_token")
UserDefaults.standard.synchronize()
let params = ["fields": "id, first_name, last_name, name, picture"]
let graphRequest = FBSDKGraphRequest(graphPath: "/me/friends", parameters: params, tokenString: UserDefaults.standard.value(forKey: "fb_token") as! String, version: nil, httpMethod: "GET")
I think it's a Facebook's bug, You need call graph api in this way:
NSString *graphPath = [NSString stringWithFormat:#"%#/videos?access_token=%#", #"me", [FBSDKAccessToken currentAccessToken].tokenString];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:graphPath parameters:dict tokenString:alreadyAuthToken version:#"v2.12" HTTPMethod:#"POST"];
Just put the access_token in request url, and other params put in param 'parameters:'
I have an app doing a facebook login, which works well, but everytime I reopen it I have to connect again to facebook to do the sign-in. I'm also using google sign-in sdk where I can call the function gSignIn.signInSilently(), is there something similar for facebook? I found this for the javascript sdk but I don't know if it's possible for the ios SDK and how to use it in swift...
The Facebook SDK automatically maintains the login state, which can be confirmed by checking for the access token.
You can check for the access using the following method:
FBSDKAccessToken.currentAccessToken()
You can check for the presence of the token which would mean that the user is logged in.
Check the docs for more details.
i've tried this
if(![FBSDKAccessToken currentAccessToken])
{
FBSDKLoginManager *manager = [[FBSDKLoginManager alloc]init];
[manager logInWithReadPermissions:#[#"public_profile", #"email",#"user_photos"] handler:^(FBSDKLoginManagerLoginResult *result,NSError *error)
{
if(error == nil)
{
NSLog(#"Facebook - successfully login %#",result.token);
//login successfully
//do your stuff here
}
}];
}
else
{
//already login
//Do Your stuff here
}
I am saving the access token string and manually setting it on consecutive launches to bypass the re-login flow.
func loginWithFacebook() {
//Check for previous Access Token
if let accessToken = AccessToken.current {
//AccessToken was obtained during same session
getAccountDetails(withAccessToken: accessToken)
}
else if let strAuthenticationToken = UserDefaults.standard.string(forKey: "AccessToken_Facebook") {
//A previous access token string was saved so create the required AccessToken object
let accessToken = AccessToken(authenticationToken: strAuthenticationToken)
//Skip Login and directly proceed to get facebook profile data with an AccessToken
getAccountDetails(withAccessToken: accessToken)
}
else {
//Access Token was not available so do the normal login flow to obtain the Access Token
LoginManager().logIn(readPermissions: [.publicProfile, .email], viewController: nil) { loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login.")
case .success(let grantedPermissions,
let declinedPermissions,
let accessToken):
//Save Access Token string for silent login purpose later
let strAuthenticationToken = accessToken.authenticationToken
UserDefaults.standard.set(strAuthenticationToken,
forKey: "AccessToken_Facebook")
//Proceed to get facebook profile data
self.getAccountDetails(withAccessToken: accessToken)
}
}
}
}
func getAccountDetails(withAccessToken accessToken: AccessToken) {
let graphRequest: GraphRequest = GraphRequest(graphPath : "me",
parameters : ["fields" : "id, name, email"],
accessToken : accessToken,
httpMethod : GraphRequestHTTPMethod.GET,
apiVersion : GraphAPIVersion.defaultVersion)
graphRequest.start { (response, result) in
switch result {
case .success(let resultResponse):
print(resultResponse)
case .failed(let error):
print(error)
}
}
}
NOTE: For the ease of this example, the Facebook Access Token string is being saved to UserDefaults but ideally it should be saved to the Keychain.
(Swift 4 / Facebook SDK 4.30)
So I've been banging my head on this for a couple days now, and I'm hoping someone here could shed some light on this for me!
So I'm using Parse in my Swift project, and am looking to leverage the Facebook integration to make logging in and signing up a user pretty effortless.
I have managed to get as far as logging in a user, but the part where I'm stuck is that I don't know how to access the data that I requested with permissions.
In my AppDelegate Swift file, I have this block of code..
// INITIALISE FACEBOOK
let permissions = ["email", "public_profile"]
PFFacebookUtils.initializeFacebook()
PFFacebookUtils.logInWithPermissions(permissions, {
(user: PFUser!, error: NSError!) -> Void in
if user == nil {
if (error == nil) {
println("User cancelled Facebook login")
} else {
println("FB Login Error \n(error)")
}
} else if user.isNew {
println("User has signed in through Facebook!")
} else {
println("User logged in through Facebook!")
}
})
Everything is all well and dandy, and I get the "User has signed in through Facebook!" message.
According to the Parse documentation, this then creates a new User object in my database.
In my database, I see that there is indeed a new user, but the only fields that are populated are..
ObjectID - random string characters
username - random string characters
authData - a facebook type ID.
Not the username or email.
From what I have gathered, I need to now further leverage the FacebookSDK and GraphUser, but I really dont know exactly how.. or at least not in Swift.
The Parse documentation says
"The Facebook iOS SDK provides a number of helper classes for interacting with Facebook's API. Generally, you will use the FBRequest class to interact with Facebook on behalf of your logged-in user. You can read more about the Facebook SDK here.
Our library manages the user's FBSession object for you. You can simply call [PFFacebookUtils session] to access the session instance, which can then be passed to FBRequests."
But I really dont know what to type or where to type it. :(
It feels like I'm really close with this, but I'm just hitting blanks..
If someone could be kind enough to shed some light into this (how to access the details I requested permission for, i.e. full name and email) I would be incredibly grateful!
Thank you.. :)
You may try this (for Swift):
// Obtain User Data via Facebook Login
func returnUserData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"name, email"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
}
else
{
let userName: String = result.valueForKey("name") as! String
let Email: String = result.valueForKey("email") as! String
println(userName)
println(Email)
}
})
}
According to this: https://parse.com/questions/how-can-i-get-the-facebook-id-of-a-user-logged-in-with-facebook
You get the Facebook ID with this Objective-C
// After logging in with Facebook
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *facebookId = [result objectForKey:#"id"];
}
}];
Which is this in Swift (not tested)
FBRequestConnection.startForMeWithCompletionHandler { connection, result, error in
if (!error) {
let facebookId = result["id"]
// use facebookID
}
}
I'm trying to test my native iOS app and I've been having huge problems with test users. Basically it seems that the normal graph based way of creating test users doesn't work for native apps. When I try I get the following response from the server:
{
"error": {
"message": "(#15) This method is not supported for native apps",
"type": "OAuthException",
"code": 15
}
}
This seems to be supported by various posts on SO and a page on the old FB forums:
http://forum.developers.facebook.net/viewtopic.php?id=93086
People say that the only way to create test users for native apps is to create proper fake accounts on FB, which is against FB terms and conditions. Is this really my only option ? I can't believe the FB devs cannot support test accounts for native apps.
Anyone know of any legitimate way to create native app test users ?
At the top of the developer documentation for test users, a GUI for maintaining test users is also mentioned.
In addition to the Graph API functionality described below for managing test users programmatically, there is also a simple GUI in the Developer App, available on your app's Roles page as shown in the screenshots below. It exposes all of the API functions described in this document.
For some reason I don't understand, the Graph API calls aren't available if your app has an 'App Type' (under Settings -> Advanced) of Native/Desktop. But you can use the GUI instead.
You can create a new facebook test user for your app by calling the below function.
Please user your APP ID (go to this link to get your App's ID:https://developers.facebook.com/apps)
Please go to your app on facebook and get the App secret ID
-(void)createNewUser{
NSString *appID=#"Past your App ID"
NSString *appSecret=#"Past your App secret"
NSDictionary *params = #{
#"true": #"installed",
#"access_token": #"appID|appSecret",
};
NSString *path = [NSString stringWithFormat:#"/appID/accounts/test-users"];
/* make the API call */
[FBRequestConnection startWithGraphPath:path
parameters:params
HTTPMethod:#"POST"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
)
{
if (result && !error)
{
NSLog(#"Test-User created successfully: %#", result);
}
else
{
NSLog(#"Error creating test-user: %#", error);
NSLog(#"Result Error: %#", result);
}
}];
}
Please make sure you don't reveal your App secret ID to anyone and never include it in your app hardcoded like that.
Hope it helps
The following works for me using the Facebook iOS SDK v4.1.0:
// Listed as "App ID": https://developers.facebook.com/apps/
NSString *facebookAppId = #"1234_REPLACE_ME_5678";
// Listed as "App Token": https://developers.facebook.com/tools/accesstoken/
NSString *facebookAppToken = #"ABCD_REPLACE_ME_1234";
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:#"/%#/accounts/test-users",
facebookAppId]
parameters:#{#"installed" : #"true"}
tokenString:facebookAppToken
version:#"v2.3"
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
NSDictionary *testUser,
NSError *facebookError) {
if (facebookError) {
NSLog(#"Error creating test user: %#", facebookError);
} else {
NSLog(#"access_token=%#", testUser[#"access_token"]);
NSLog(#"email=%#", testUser[#"email"]);
NSLog(#"user_id=%#", testUser[#"id"]);
NSLog(#"login_url=%#", testUser[#"login_url"]);
NSLog(#"password=%#", testUser[#"password"]);
}
}];
When successful, the output is then something like this:
access_token=CACQSQXq3KKYeahRightYouDontGetToLookAtMyAccessTokenspBkJJK16FHUPBTCKIauNO8wZDZD
email=aqhndli_huisen_1430877783#tfbnw.net
user_id=1384478845215781
login_url=https://developers.facebook.com/checkpoint/test-user-login/1384478845215781/
password=1644747383820
Swift4 version.
import FBSDKCoreKit
// App Token can be found here: https://developers.facebook.com/tools/accesstoken/
let appToken = "--EDITED--"
let appID = "--EDITED--"
let parameters = ["access_token": appID + "|" + appToken, "name": "Integration Test"]
let path = "/\(appID)/accounts/test-users"
guard let request = FBSDKGraphRequest(graphPath: path, parameters: parameters, httpMethod: "POST") else {
fatalError()
}
request.start { _, response, error in
if let error = error {
// Handle error.
return
}
if let response = response as? [AnyHashable: Any],
let userID = response["id"] as? String,
let token = response["access_token"] as? String,
let email = response["email"] as? String {
// Handle success response.
} else {
// Handle unexpected response.
}
}
You can use Facebook's Test User API https://developers.facebook.com/docs/test_users/ to create test users, just be sure to use the same App id.
Given a APP_ID and APP_SECRET, the following gives us an APP_ACCESS_TOKEN
curl -vv 'https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=client_credentials'
then we can use the token to create test users:
curl 'https://graph.facebook.com/APP_ID/accounts/test-users?installed=true&name=NEW_USER_NAME&locale=en_US&permissions=read_stream&method=post&access_token=APP_ACCESS_TOKEN
in the response body to this command will the new users' email and password.