How to get user email address via Twitter API in iOS?
Asked Answered
G

5

6

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);
Gemmell answered 28/10, 2013 at 7:38 Comment(2)
Your code sample appears to be incomplete..?Aniseikonia
I like the FHSTwitterEngine hahaGimel
S
13

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.

Stander answered 28/10, 2013 at 8:12 Comment(3)
This is no longer correct. A user's email address can be obtained through: /1.1/account/verify_credentials.json?include_email=trueTerpsichorean
Link doesn't exist @VirussmcaHampstead
dev.twitter.com/rest/reference/get/account/verify_credentials can be used to get the email id but your app has to be whitelisted firstByington
G
4

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 [email protected] 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 [email protected] 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:

    1. On the 'Settings' tab, add a terms of service and privacy policy URL
    2. 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 !!!

Gill answered 26/5, 2015 at 11:2 Comment(0)
O
2

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.

Orthohydrogen answered 21/6, 2014 at 6:50 Comment(0)
S
0

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))");
    }
}
}
Shamus answered 14/2, 2019 at 10:0 Comment(0)
A
0

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)");
            }
        })

    }
Alesha answered 11/9, 2019 at 12:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.