How to get user email address via Twitter API in iOS? - ios

I have tried multiple SDK's but was unable to get an email ID from any of the resources. I have tried FHSTwitterEngine for this purpose but I didn't get the solution.
FHSTwitterEngine *twitterEngine = [FHSTwitterEngine sharedEngine];
NSString *username = [twitterEngine loggedInUsername]; //self.engine.loggedInUsername;
NSString *key = [twitterEngine accessToken].key;
NSString *secrete = [twitterEngine accessToken].secret;
if (username.length > 0)
{
NSDictionary *userProfile = [[FHSTwitterEngine sharedEngine] getProfileUsername:username];
NSLog(#"userProfile: %#", userProfile);

EDIT
After Twitter has updated APIs, Now user can get Email using TWTRShareEmailViewController class.
// Objective-C
if ([[Twitter sharedInstance] session]) {
TWTRShareEmailViewController* shareEmailViewController = [[TWTRShareEmailViewController alloc] initWithCompletion:^(NSString* email, NSError* error) {
NSLog(#"Email %#, Error: %#", email, error);
}];
[self presentViewController:shareEmailViewController animated:YES completion:nil];
} else {
// TODO: Handle user not signed in (e.g. attempt to log in or show an alert)
}
// Swift
if Twitter.sharedInstance().session {
let shareEmailViewController = TWTRShareEmailViewController() { email, error in
println("Email \(email), Error: \(error)")
}
self.presentViewController(shareEmailViewController, animated: true, completion: nil)
} else {
// TODO: Handle user not signed in (e.g. attempt to log in or show an alert)
}
NOTES:
Even if the user grants access to her email address, it is not guaranteed you will get an email address. For example, if someone signed up for Twitter with a phone number instead of an email address, the email field may be empty. When this happens, the completion block will pass an error because there is no email address available.
Twitter Dev Ref
PAST
There is NO way you can get email address of a twitter user.
The Twitter API does not provide the user's email address as part of the OAuth token negotiation process nor does it offer other means to obtain it.
Twitter Doc.

You will have to use Twitter framework. Twitter has provided a beautiful framework for that, you just have to integrate it in your app.
To get user email address, your application should be whitelisted. Here is the link. Go to use this form. You can either send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App etc..They will respond within 2-3 working days.
Here is the story how I got whitelisted by conversation with Twitter support team:
Send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App. Mention in mail that you want to access user email adress inside your App.
They will review your App and reply to you withing 2-3 business days.
Once they say that your App is whitelisted, update your App's settings in Twitter Developer portal. Sign in to apps.twitter.com and:
On the 'Settings' tab, add a terms of service and privacy policy URL
On the 'Permissions' tab, change your token's scope to request email. This option will only been seen, once your App gets whitelisted.
Put your hands on code
Use of Twitter framework:
Get user email address
-(void)requestUserEmail
{
if ([[Twitter sharedInstance] session]) {
TWTRShareEmailViewController *shareEmailViewController =
[[TWTRShareEmailViewController alloc]
initWithCompletion:^(NSString *email, NSError *error) {
NSLog(#"Email %# | Error: %#", email, error);
}];
[self presentViewController:shareEmailViewController
animated:YES
completion:nil];
} else {
// Handle user not signed in (e.g. attempt to log in or show an alert)
}
}
Get user profile
-(void)usersShow:(NSString *)userID
{
NSString *statusesShowEndpoint = #"https://api.twitter.com/1.1/users/show.json";
NSDictionary *params = #{#"user_id": userID};
NSError *clientError;
NSURLRequest *request = [[[Twitter sharedInstance] APIClient]
URLRequestWithMethod:#"GET"
URL:statusesShowEndpoint
parameters:params
error:&clientError];
if (request) {
[[[Twitter sharedInstance] APIClient]
sendTwitterRequest:request
completion:^(NSURLResponse *response,
NSData *data,
NSError *connectionError) {
if (data) {
// handle the response data e.g.
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&jsonError];
NSLog(#"%#",[json description]);
}
else {
NSLog(#"Error code: %ld | Error description: %#", (long)[connectionError code], [connectionError localizedDescription]);
}
}];
}
else {
NSLog(#"Error: %#", clientError);
}
}
Hope it helps !!!

If you'd like a user's email address, you'll need to ask a user for it within the confines of your own application and service. The Twitter API does not provide the user's email address as part of the OAuth token negotiation process nor does it offer other means to obtain it.

In Swift 4.2 and Xcode 10.1
It's getting email also.
import TwitterKit
#IBAction func onClickTwitterSignin(_ sender: UIButton) {
TWTRTwitter.sharedInstance().logIn { (session, error) in
if (session != nil) {
let name = session?.userName ?? ""
print(name)
print(session?.userID ?? "")
print(session?.authToken ?? "")
print(session?.authTokenSecret ?? "")
let client = TWTRAPIClient.withCurrentUser()
client.requestEmail { email, error in
if (email != nil) {
let recivedEmailID = email ?? ""
print(recivedEmailID)
}else {
print("error--: \(String(describing: error?.localizedDescription))");
}
}
let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
self.navigationController?.pushViewController(storyboard, animated: true)
}else {
print("error: \(String(describing: error?.localizedDescription))");
}
}
}

Swift 3-4
#IBAction func btnTwitterAction(_ sender: Any) {
TWTRTwitter.sharedInstance().logIn(completion: { (session, error) in
if (session != nil) {
print("signed in as \(String(describing: session?.userName))");
if let mySession = session{
let client = TWTRAPIClient.withCurrentUser()
//To get User name and email
client.requestEmail { email, error in
if (email != nil) {
print("signed in as \(String(describing: session?.userName))");
let firstName = session?.userName ?? "" // received first name
let lastName = session?.userName ?? "" // received last name
let recivedEmailID = email ?? "" // received email
}else {
print("error: \(String(describing: error?.localizedDescription))");
}
}
//To get user profile picture
client.loadUser(withID: session?.userID, completion: { (userData, error) in
if (userData != nil) {
let fullName = userData.name //Full Name
let userProfileImage = userData.profileImageLargeURL //User Profile Image
let userTwitterProfileUrl = userData?.profileURL // User TwitterProfileUrl
}
})
}
} else {
print("error: \(error?.localizedDescription)");
}
})
}

Related

QuickBlox video chat: QBRequest.logInWithUserEmail vs QBChat.instance().connectWithUser

I have a simple QuickBlox chat app built by following the iOS tutorial:
http://quickblox.com/developers/Sample-webrtc-ios#Sources
I've successfully created a user and logged them in. However, I run into an error when I try to initiate a session: "You have to be logged in in order to use Chat API".
let newSession: QBRTCSession = QBRTCClient.instance().createNewSessionWithOpponents(["12498970"], withConferenceType: QBRTCConferenceType.Video)
I'm able to resolve this by adding QBChat.instance().connectWithUser each time I open it:
QBChat.instance().connectWithUser(user!) { (error) in
if error != nil {
print("error: \(error)")
}
else {
print("login to chat succeeded")
}
}
But somehow this seems weird because I have to either cache the password or prompt the user to enter their password each time the app opens. It seems strange that the QBSession.currentSession().currentUser is still valid, but the QBChat user has been invalidated. What is the best practice for accomplishing this? In all the samples, the passwords are hardcoded. This doesn't seem like a great solution.
I ended up following examples in Q-municate, which is an app the Quickblox folks built to basically demonstrate their whole package, as well as provide an actual solution for whatever your chat needs are. I have some other custom stuff and don't need a lot of the functionality so I'm still trying to dig through the details of how they implement it. The link to Q-municate:
http://quickblox.com/developers/Q-municate#1._Get_the_source_code.
In their login flow, they use the QMApi module written for Q-municate:
[[QMApi instance] loginWithEmail:email
password:password
rememberMe:weakSelf.rememberMeSwitch.on
completion:^(BOOL success)
{
[SVProgressHUD dismiss];
if (success) {
[[QMApi instance] setAutoLogin:weakSelf.rememberMeSwitch.on
withAccountType:QMAccountTypeEmail];
[weakSelf performSegueWithIdentifier:kTabBarSegueIdnetifier
sender:nil];
}
}];
In loginWithEmail, their settingsManager caches this login:
[weakSelf.settingsManager setLogin:email andPassword:password];
which is actually just a way to cache the password in SSKeyChain.
[SSKeychain setPassword:password forService:kQMAuthServiceKey account:login];
Later, when you return to the app, they call autologin:
if (!self.isAuthorized) {
if (self.settingsManager.accountType == QMAccountTypeEmail && self.settingsManager.password && self.settingsManager.login) {
NSString *email = self.settingsManager.login;
NSString *password = self.settingsManager.password;
[self loginWithEmail:email password:password rememberMe:YES completion:completion];
}
else if (self.settingsManager.accountType == QMAccountTypeFacebook) {
[self loginWithFacebook:completion];
}
else {
if (completion) completion(NO);
}
}
else {
if (completion) completion(YES);
}
where self.settingsManager.password pulls the password from SSKeychain:
NSString *password = [SSKeychain passwordForService:kQMAuthServiceKey account:self.login];
autoLogin is called when the main chat tab is loaded. That makes our classic call to connectToChat:
[[QMApi instance] autoLogin:^(BOOL success) {
if (!success) {
[[QMApi instance] logoutWithCompletion:^(BOOL succeed) {
//
[weakSelf performSegueWithIdentifier:#"SplashSegue" sender:nil];
}];
} else {
// subscribe to push notifications
[[QMApi instance] subscribeToPushNotificationsForceSettings:NO complete:^(BOOL subscribeToPushNotificationsSuccess) {
if (!subscribeToPushNotificationsSuccess) {
[QMApi instance].settingsManager.pushNotificationsEnabled = NO;
}
}];
[weakSelf connectToChat];
}
}];
So technically the docs are doing the right thing by logging in to chat every time the app opens and chat is no longer connected. There's just a much more complex but secure way to store that password so the user doesn't have to reenter it.
TLDR: The way it works in my code (and in swift) is:
On login:
QBRequest.logInWithUserEmail(email, password: password, successBlock: { (response, user) in
SSKeychain.setPassword(password, forService: "kMyAppLoginServiceKey", account: email)
}) { (errorResponse) in
print("Error: \(errorResponse)")
self.simpleAlert("Could not log in", defaultMessage: nil, error: nil)
}
Whenever the chat view loads:
if !QBChat.instance().isConnected() {
QBRTCClient.initializeRTC()
QBRTCClient.instance().addDelegate(self)
let user = QBSession.currentSession().currentUser
let password = SSKeychain.passwordForService("kMyAppLoginServiceKey", account: user?.email!)
user!.password = password
QBChat.instance().addDelegate(self)
QBChat.instance().connectWithUser(user!) { (error) in
if error != nil {
print("error: \(error)")
}
else {
print("login to chat succeeded")
}
}
}

How to get email from twitter by fabric in iOS 9? [duplicate]

I have integrated twitter kit in my ios app by following https://dev.twitter.com/twitter-kit/ios/configure this. I could sign-in after authentication and see my twitter name easily but now i want to retrieve my email address so i used TWTRShareEmailViewController which presents user a share email view which returns null. I went through the docs where they mentioned about my app to be whitelisted for requesting email permission and said to fill up this form https://support.twitter.com/forms/platform am not getting what to do next? how to get i user email permission exactly? Suggest any help. Thanks in advance.
I didn't find a specific form to ask to be whitelisted neither. I went on their form link https://support.twitter.com/forms/platform and I checked the "I have an API policy question not covered by these points" option. They responded a few days after and asked me more information about the application and its app ID. I'm actually waiting for their answer.
EDIT:
So after several (a lot) emails with support#fabric.io and a few bugs I finally got whitelisted. But the option is currently unavailable with Fabric so you'll have to create a Twitter app on apps.twitter.com. Just send a mail with your app ID or your keys. They'll probably ask you a quick description of your app and it shouldn't take so much time to be whitelisted. Good luck!
After having a conversation with sdk-feedback#twitter.com, I got my App whitelisted. Here is the story:
Send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App. Mention in mail that you want to access user email address inside your App.
They will review your App and reply to you within 2-3 business days.
Once they say that your App is whitelisted, update your App's settings in Twitter Developer portal. Sign in to apps.twitter.com and:
On the 'Settings' tab, add a terms of service and privacy policy URL
On the 'Permissions' tab, change your token's scope to request email. This option will only been seen, once your App gets whitelisted.
It's time to code:
-(void)requestUserEmail
{
if ([[Twitter sharedInstance] session]) {
TWTRShareEmailViewController *shareEmailViewController =
[[TWTRShareEmailViewController alloc]
initWithCompletion:^(NSString *email, NSError *error) {
NSLog(#"Email %# | Error: %#", email, error);
}];
[self presentViewController:shareEmailViewController
animated:YES
completion:nil];
} else {
// Handle user not signed in (e.g. attempt to log in or show an alert)
}
}
Hope it helps !!!
Send email to sdk-feedback#twitter.com to whitelist your twitter login app first.
Swift 3.0 Code with fabric
#IBAction func btnTwitterAction(_ sender: AnyObject) {
Twitter.sharedInstance().logIn { (session, error) in
if session != nil {
print("signed in as \(session!.userName)");
let client = TWTRAPIClient.withCurrentUser()
let request = client.urlRequest(withMethod: "GET",
url: "https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true",
parameters: ["include_email": "true", "skip_status": "true"],
error: nil)
client.sendTwitterRequest(request) { response, data, connectionError in
if (connectionError == nil) {
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
print("Json response: ", json)
let firstName = json["name"]
let lastName = json["screen_name"]
let email = json["email"]
print("First name: ",firstName)
print("Last name: ",lastName)
print("Email: ",email)
} catch {
}
}
else {
print("Error: \(connectionError)")
}
}
} else {
NSLog("Login error: %#", error!.localizedDescription);
}
}
}
How to get email id in twitter ?
Step 1 : got to https://apps.twitter.com/app/
Step 2 : click on ur app > click on permission tab .
Step 3 : here check the email box
I've faced the same issue recently
Here is what you should try if you are using new twitter kit
Go to
https://apps.twitter.com/
Select permissions tab
Set it to Read Only
Code :
Twitter.sharedInstance().logIn(withMethods: [.webBased,.systemAccounts,.all]) {(session, error) -> Void in
if (session != nil) {
print("signed in as \(session?.userName)");
let client = TWTRAPIClient(userID: session?.userName)
client.loadUser(withID: (session?.userID)!, completion: { (user, error) in
let twitterClient = TWTRAPIClient.withCurrentUser()
let request = twitterClient.urlRequest(withMethod: "GET",
url: "https://api.twitter.com/1.1/account/verify_credentials.json",
parameters: ["include_email": "true", "skip_status": "true"],
error: nil)
twitterClient.sendTwitterRequest(request) { response, data, connectionError in
print(data!)
let s :String = String(data: data! as Data, encoding: String.Encoding.utf8)!
//
// let json = try JSONSerialization.jsonObject(with: responseData as Data, options: JSONSerialization.ReadingOptions.mutableLeaves) as? [String:AnyObject]
//
Twitter.sharedInstance().sessionStore.logOutUserID((session?.userID)!)
if let data = s.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json!)
} catch {
print("Something went wrong")
}
}
}
})
} else {
}

iOS Parse.com Facebook Login - valid email address error

Using the sample code, I continually get a nil user and an error in the block for the login:
2015-11-09 17:39:16.017[90448:3746935] [Error]: You must use a valid email address. (Code: 142, Version: 1.9.1)
Printing description of error:
Error Domain=Parse Code=142 "You must use a valid email address." UserInfo=0x7fb403c39f20 {code=142, temporary=0, error=You must use a valid email address., NSLocalizedDescription=You must use a valid email address.}
Here's the code:
FBSDKAccessToken *accessToken = [FBSDKAccessToken currentAccessToken];
if (accessToken)
{
[PFFacebookUtils logInInBackgroundWithAccessToken:accessToken block:^(PFUser * _Nullable user, NSError * _Nullable error) {
if (!user) {
NSLog(#"Facebook login cancelled.");
} else {
NSLog(#"User now has publish permissions!");
[self loadFBAccountInfo];
}
}];
}
else
{
[PFFacebookUtils logInInBackgroundWithReadPermissions:#[ #"email", #"public_profile" ] block:^(PFUser *user, NSError *error) { // , #"publish_actions"
if (!user) {
NSLog(#"Facebook login cancelled.");
} else {
NSLog(#"User now has publish permissions!");
[self loadFBAccountInfo];
}
}];
}
Any help is appreciated!
Sorry, the error was in the cloud code which required an email address - when a user is first created via the Facebook route, it doesn't have an email address...
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
var email = request.object.get('email');
if (!email) {
response.error('You must use a valid email address.');
} else {
response.success();
}
});

how to request permission to retrieve user's email using twitter kit version 1.2.0 in ios8?

I have integrated twitter kit in my ios app by following https://dev.twitter.com/twitter-kit/ios/configure this. I could sign-in after authentication and see my twitter name easily but now i want to retrieve my email address so i used TWTRShareEmailViewController which presents user a share email view which returns null. I went through the docs where they mentioned about my app to be whitelisted for requesting email permission and said to fill up this form https://support.twitter.com/forms/platform am not getting what to do next? how to get i user email permission exactly? Suggest any help. Thanks in advance.
I didn't find a specific form to ask to be whitelisted neither. I went on their form link https://support.twitter.com/forms/platform and I checked the "I have an API policy question not covered by these points" option. They responded a few days after and asked me more information about the application and its app ID. I'm actually waiting for their answer.
EDIT:
So after several (a lot) emails with support#fabric.io and a few bugs I finally got whitelisted. But the option is currently unavailable with Fabric so you'll have to create a Twitter app on apps.twitter.com. Just send a mail with your app ID or your keys. They'll probably ask you a quick description of your app and it shouldn't take so much time to be whitelisted. Good luck!
After having a conversation with sdk-feedback#twitter.com, I got my App whitelisted. Here is the story:
Send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App. Mention in mail that you want to access user email address inside your App.
They will review your App and reply to you within 2-3 business days.
Once they say that your App is whitelisted, update your App's settings in Twitter Developer portal. Sign in to apps.twitter.com and:
On the 'Settings' tab, add a terms of service and privacy policy URL
On the 'Permissions' tab, change your token's scope to request email. This option will only been seen, once your App gets whitelisted.
It's time to code:
-(void)requestUserEmail
{
if ([[Twitter sharedInstance] session]) {
TWTRShareEmailViewController *shareEmailViewController =
[[TWTRShareEmailViewController alloc]
initWithCompletion:^(NSString *email, NSError *error) {
NSLog(#"Email %# | Error: %#", email, error);
}];
[self presentViewController:shareEmailViewController
animated:YES
completion:nil];
} else {
// Handle user not signed in (e.g. attempt to log in or show an alert)
}
}
Hope it helps !!!
Send email to sdk-feedback#twitter.com to whitelist your twitter login app first.
Swift 3.0 Code with fabric
#IBAction func btnTwitterAction(_ sender: AnyObject) {
Twitter.sharedInstance().logIn { (session, error) in
if session != nil {
print("signed in as \(session!.userName)");
let client = TWTRAPIClient.withCurrentUser()
let request = client.urlRequest(withMethod: "GET",
url: "https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true",
parameters: ["include_email": "true", "skip_status": "true"],
error: nil)
client.sendTwitterRequest(request) { response, data, connectionError in
if (connectionError == nil) {
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
print("Json response: ", json)
let firstName = json["name"]
let lastName = json["screen_name"]
let email = json["email"]
print("First name: ",firstName)
print("Last name: ",lastName)
print("Email: ",email)
} catch {
}
}
else {
print("Error: \(connectionError)")
}
}
} else {
NSLog("Login error: %#", error!.localizedDescription);
}
}
}
How to get email id in twitter ?
Step 1 : got to https://apps.twitter.com/app/
Step 2 : click on ur app > click on permission tab .
Step 3 : here check the email box
I've faced the same issue recently
Here is what you should try if you are using new twitter kit
Go to
https://apps.twitter.com/
Select permissions tab
Set it to Read Only
Code :
Twitter.sharedInstance().logIn(withMethods: [.webBased,.systemAccounts,.all]) {(session, error) -> Void in
if (session != nil) {
print("signed in as \(session?.userName)");
let client = TWTRAPIClient(userID: session?.userName)
client.loadUser(withID: (session?.userID)!, completion: { (user, error) in
let twitterClient = TWTRAPIClient.withCurrentUser()
let request = twitterClient.urlRequest(withMethod: "GET",
url: "https://api.twitter.com/1.1/account/verify_credentials.json",
parameters: ["include_email": "true", "skip_status": "true"],
error: nil)
twitterClient.sendTwitterRequest(request) { response, data, connectionError in
print(data!)
let s :String = String(data: data! as Data, encoding: String.Encoding.utf8)!
//
// let json = try JSONSerialization.jsonObject(with: responseData as Data, options: JSONSerialization.ReadingOptions.mutableLeaves) as? [String:AnyObject]
//
Twitter.sharedInstance().sessionStore.logOutUserID((session?.userID)!)
if let data = s.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json!)
} catch {
print("Something went wrong")
}
}
}
})
} else {
}

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