Get user profile details (especially email address) from Twitter in iOS
Asked Answered
B

5

3

I am aiming to get a user's details based on his/her Twitter account. Now first of all, let me explain what I want to do.

In my case, user will be presented an option to Sign-up with Twitter account. So, based on user's Twitter account, I want to be able to get user details (e.g. email-id, name, profile picture, birth date, gender etc..) and save those details in database. Now, many people will probably suggest me to use ACAccount and ACAccountStore, a class that provides an interface for accessing, manipulating, and storing accounts. But in my case, I want to sign up user, even if user has not configured an account for Twitter in iOS Settings App. I want user to navigate to login screen of Twitter (in Safari or in App itself, or using any other alternative).

I have also referred the documentation of Twitter having API list here. But I am a lot confused how user should be presented a login screen to log into the Twitter account and how I will get profile information. Should I use UIWebView, or redirect user to Safari or adopt another way for that ?

Bergamot answered 14/5, 2015 at 10:27 Comment(0)
D
3

Twitter has provided a beautiful framework for that, you just have to integrate it in your app.

https://dev.twitter.com/twitter-kit/ios

It has a simple Login Method:-

// Objective-C
TWTRLogInButton* logInButton =  [TWTRLogInButton
                                     buttonWithLogInCompletion:
                                     ^(TWTRSession* session, NSError* error) {
    if (session) {
         NSLog(@"signed in as %@", [session userName]);
    } else {
         NSLog(@"error: %@", [error localizedDescription]);
    }
}];
logInButton.center = self.view.center;
[self.view addSubview:logInButton];

This is the process to get user profile information:-

/* Get user info */
        [[[Twitter sharedInstance] APIClient] loadUserWithID:[session userID]
                                                  completion:^(TWTRUser *user,
                                                               NSError *error)
        {
            // handle the response or error
            if (![error isEqual:nil]) {
                NSLog(@"Twitter info   -> user = %@ ",user);
                NSString *urlString = [[NSString alloc]initWithString:user.profileImageLargeURL];
                NSURL *url = [[NSURL alloc]initWithString:urlString];
                NSData *pullTwitterPP = [[NSData alloc]initWithContentsOfURL:url];

                UIImage *profImage = [UIImage imageWithData:pullTwitterPP];


            } else {
                NSLog(@"Twitter error getting profile : %@", [error localizedDescription]);
            }
        }];

I think rest you can find from Twitter Kit Tutorial, it also allows to request a user’s email, by calling the TwitterAuthClient#requestEmail method, passing in a valid TwitterSession and Callback.

Deterrent answered 14/5, 2015 at 10:36 Comment(6)
We can't get email using Twitter APIs. Twitter don't allow exposing user email address.Bergamot
Who said it is not possible, Twitter Kit allows to request a user’s email, call the TwitterAuthClient#requestEmail method, passing in a valid TwitterSession and Callback. Read carefully the Twitter Kit doc then comment.Deterrent
I referred to lots of posts saying that it's not possible and I also read the documentation of Twitter. As per their documentation, if we need a user email address then our App should be shortlisted by then...Bergamot
I decided to use Twitter kit. Answer accepted... Everything works fine. Just I will have to make my App white-listed on Twitter to request user his/her email address. Presently I am getting nil as email address.Bergamot
@Pratik Check the 3rd comment, email fetching is possible, you just have to read the docs carefully.Deterrent
Vizllx, I explored a lot in web but could not find a way to call the TwitterAuthClient#requestEmail method as suggested by you. Also, as per Twitter documentation, we will have to fill up a form here. But there is no option for requesting user email. Please help me. I am desperate to the solution.Bergamot
B
5

Finally, after having a long conversation with [email protected], I got my App whitelisted. Here is the story:

  • 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 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:

    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:

Agree with statement of Vizllx: "Twitter has provided a beautiful framework for that, you just have to integrate it in your app."

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 !!!

Bergamot answered 27/5, 2015 at 8:6 Comment(1)
@NSPrtatik I saw your answers for various posts. Can you please see this question #32758567Sorcha
T
4

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

enter image description here

Time answered 17/10, 2017 at 10:2 Comment(0)
S
3

In Twitter you can get user_name and user_id only. It is that much secure that you can't fetch email id, birth date, gender etc.., compare to Facebook, Twitter is very confidential for supplying the data.

need ref: link1.

Supporting answered 14/5, 2015 at 10:31 Comment(5)
In the documentation of Twitter, they have mentioned the method to get user email id. Also I got some example to download user profile pictures.Bergamot
ya we can fetch user picture when u passing the screen_name after that we fetch the image , in here I attach the image please refer that linkSupporting
in my knowledge I used twitter api in last 8 or 9 projects, we can't fetch the email Id in Account framework please see this ref link2Supporting
may be some third_parties provide this , I am not seen, if you need anything I surely hope with you friendSupporting
Anbu.Karthik, please check my added answer. It's possible and I am now able to get user email address.Bergamot
D
3

Twitter has provided a beautiful framework for that, you just have to integrate it in your app.

https://dev.twitter.com/twitter-kit/ios

It has a simple Login Method:-

// Objective-C
TWTRLogInButton* logInButton =  [TWTRLogInButton
                                     buttonWithLogInCompletion:
                                     ^(TWTRSession* session, NSError* error) {
    if (session) {
         NSLog(@"signed in as %@", [session userName]);
    } else {
         NSLog(@"error: %@", [error localizedDescription]);
    }
}];
logInButton.center = self.view.center;
[self.view addSubview:logInButton];

This is the process to get user profile information:-

/* Get user info */
        [[[Twitter sharedInstance] APIClient] loadUserWithID:[session userID]
                                                  completion:^(TWTRUser *user,
                                                               NSError *error)
        {
            // handle the response or error
            if (![error isEqual:nil]) {
                NSLog(@"Twitter info   -> user = %@ ",user);
                NSString *urlString = [[NSString alloc]initWithString:user.profileImageLargeURL];
                NSURL *url = [[NSURL alloc]initWithString:urlString];
                NSData *pullTwitterPP = [[NSData alloc]initWithContentsOfURL:url];

                UIImage *profImage = [UIImage imageWithData:pullTwitterPP];


            } else {
                NSLog(@"Twitter error getting profile : %@", [error localizedDescription]);
            }
        }];

I think rest you can find from Twitter Kit Tutorial, it also allows to request a user’s email, by calling the TwitterAuthClient#requestEmail method, passing in a valid TwitterSession and Callback.

Deterrent answered 14/5, 2015 at 10:36 Comment(6)
We can't get email using Twitter APIs. Twitter don't allow exposing user email address.Bergamot
Who said it is not possible, Twitter Kit allows to request a user’s email, call the TwitterAuthClient#requestEmail method, passing in a valid TwitterSession and Callback. Read carefully the Twitter Kit doc then comment.Deterrent
I referred to lots of posts saying that it's not possible and I also read the documentation of Twitter. As per their documentation, if we need a user email address then our App should be shortlisted by then...Bergamot
I decided to use Twitter kit. Answer accepted... Everything works fine. Just I will have to make my App white-listed on Twitter to request user his/her email address. Presently I am getting nil as email address.Bergamot
@Pratik Check the 3rd comment, email fetching is possible, you just have to read the docs carefully.Deterrent
Vizllx, I explored a lot in web but could not find a way to call the TwitterAuthClient#requestEmail method as suggested by you. Also, as per Twitter documentation, we will have to fill up a form here. But there is no option for requesting user email. Please help me. I am desperate to the solution.Bergamot
A
2

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))");
            }
        }
            //To get profile image url and screen name
            let twitterClient = TWTRAPIClient(userID: session?.userID)
                twitterClient.loadUser(withID: session?.userID ?? "") {(user, error) in
                print(user?.profileImageURL ?? "")
                print(user?.profileImageLargeURL ?? "")
                print(user?.screenName ?? "")
            }
        let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as!   SecondViewController
        self.navigationController?.pushViewController(storyboard, animated: true)
    }else {
        print("error: \(String(describing: error?.localizedDescription))");
    }
    }
}

Follow the Harshil Kotecha answer.

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

enter image description here

If you want to logout

let store = TWTRTwitter.sharedInstance().sessionStore
if let userID = store.session()?.userID {
    print(store.session()?.userID ?? "")
    store.logOutUserID(userID)
    print(store.session()?.userID ?? "")
    self.navigationController?.popToRootViewController(animated: true)
}
Archibald answered 14/2, 2019 at 10:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.